Link to home
Start Free TrialLog in
Avatar of ambuli
ambuliFlag for United States of America

asked on

Encryption using private key

Hi Experts,

I have a key pair ( public and private keys) generated through Java.  Now, I need to try out with encrypting and decrypting using these keys.    Can you point me to good tutorial or example of how to do this?



        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ambuli

ASKER

Hi,

I have the following code snippet and it is working.  But, instead reading the keys from the KeyPairGenerator, I want to supply mine which is a String.. PEM format.


package com.mitel.cert;
import java.security.*;
import java.security.interfaces.*;
 
import javax.crypto.Cipher;
 
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
public class Test
{
 
    private final RSAPrivateCrtKey rsaPriv;
    private final RSAPublicKey rsaPub;
    
    public Test() throws Exception
    {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        KeyPair kp = kpg.generateKeyPair();
        rsaPriv = (RSAPrivateCrtKey) kp.getPrivate();
        rsaPub = (RSAPublicKey) kp.getPublic();        
        
    }
 
    public byte [] encrypt (byte [] toEncrypt) throws Exception
    {
        final AsymmetricBlockCipher rsaCipher = new PKCS1Encoding(new RSAEngine());
        rsaCipher.init(true, new RSAKeyParameters(false, rsaPub.getModulus(), rsaPub.getPublicExponent()));
        return rsaCipher.processBlock(toEncrypt, 0, toEncrypt.length);
    }
    
    public byte[] decrypt(byte[] toDecrypt) throws Exception 
    {
        Cipher rsaCipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");
        rsaCipher.init(Cipher.DECRYPT_MODE, rsaPriv);
        return rsaCipher.doFinal(toDecrypt);
    }
    public static void main(String[] args) throws Exception
    {
        Security.addProvider(new BouncyCastleProvider());
        Test bctoy = new Test();
        byte [] message = "Hello, World, how are you?".getBytes("UTF-8");
        byte [] encrypted = bctoy.encrypt(message);
        System.out.println(encrypted);
        byte [] decrypted = bctoy.decrypt(encrypted);
        System.out.println(new String(decrypted, "UTF-8"));
    }
 
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial