Following java code can be used to encrypt a message with RSA and RSA/ECB/PKCS1Padding.
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
public class RSAEncryptionTest {
private PrivateKey privateKey;
private PublicKey publicKey;
public RSAEncryptionTest() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair pair = generator.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();
} catch (Exception e) {
e.printStackTrace();
}
}
public String encrypt(String message) throws Exception{
byte[] messageToBytes = message.getBytes();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] encryptedBytes = cipher.doFinal(messageToBytes);
return encode(encryptedBytes);
}
private String encode(byte[] data){
return Base64.getEncoder().encodeToString(data);
}
public String decrypt(String encryptedMessage) throws Exception{
byte[] encryptedBytes = decode(encryptedMessage);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE,privateKey);
byte[] decryptedMessage = cipher.doFinal(encryptedBytes);
return new String(decryptedMessage,"UTF8");
}
private byte[] decode(String data){
return Base64.getDecoder().decode(data);
}
public static void main(String[] args) {
RSAEncryptionTest rsa = new RSAEncryptionTest();
try{
String encryptedMessage = rsa.encrypt("Hello World");
String decryptedMessage = rsa.decrypt(encryptedMessage);
System.out.println("Encrypted: "+encryptedMessage);
System.out.println("Decrypted: "+decryptedMessage);
} catch (Exception e){
e.printStackTrace();
}
}
}
Output
Encrypted: RMMIeSHL7I4sTP5gIwm1SJ9MWYFwHH3uauM7fdzd59mskZMxMDhBYkfhE7/qOz6FPxKMd1Fwvb9JY2P4+31Rgidt3n9pQMpd/Be6gLAfuxxGhpE2Ytt7pKePyzUziUZRSg/C8ygkVF4+LcXU36xE/+JMSXAwd3D4fRq3HGs4wdY=
Decrypted: Hello World
0 Comments