Let us do the same example we did in the previous post, this time with RSA.
In your /src/org/confucius folder, create a class RSAEncryption.java, like this:
package org.confucius;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSAEncryption {
public static void main(String[] args) {
String secretMessageString = "For your eyes only...";
try {
KeyPairGenerator kpg;
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
// Encrypt
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] secretMessage = secretMessageString.getBytes();
byte[] encryptedMessage = encryptCipher.doFinal(secretMessage);
System.out.println("Encrypted Message = " + new String(encryptedMessage));
// Decrypt
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, (Key) privateKey);
byte[] decryptedMessage = decryptCipher.doFinal(encryptedMessage);
System.out.println("Decrypted message = " + new String(decryptedMessage));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
}
If you run this program (R-click in navigator view, select Run As --> Java application) you will see the encrypted and decrypted string printed to the console.
1 comment:
I executed the same code in my application and it worked fine. I am so glad that I found this post. It saved me so much time.
digital certificates
Post a Comment