Encryption and decryption with private key in Java

Nadendla picture Nadendla · May 23, 2014 · Viewed 34.1k times · Source

After I have read articles about Cryptography(Symmetric and Asymmetric) methods.Many articles are telling that Private key is used to encrypt and decrypt data.Public key is used to encrypt data.But When I try to start implementing in Java I can't able to use private key to encrypt and decrypt data(I am using RSA Algorithm)? If it is possible please provide me a link .If it doesn't support, please answer why it doesn't support?

//Encrypt

Cipher encrypt=Cipher.getInstance("RSA");
encrypt.init(Cipher.ENCRYPT_MODE, privatekey);
byte[] encryptedMessage=encrypt.doFinal(msg.getBytes());

//Decrypt

Cipher decrypt=Cipher.getInstance("RSA");
decrypt.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessage=decrypt.doFinal(encryptedMessage);

Answer

Maarten Bodewes picture Maarten Bodewes · May 26, 2014

To perform RSA encryption you need to encrypt with the public key and decrypt with the private key. Furthermore, you should use a well defined padding method, such as PKCS#1 v1.5 compatible padding or - if available - OAEP padding.

Encryption with an RSA private key makes no sense, as anybody with the public key can decrypt. There is something called "raw RSA" which is basically modular exponentiation, but that should only be used with another padding scheme to generate signatures. In that case you want everybody with a public key to "decrypt" to verify the signature.

More information here and here.

So encryption is:

// specify mode and padding instead of relying on defaults (use OAEP if available!)
Cipher encrypt=Cipher.getInstance("RSA/ECB/PKCS1Padding");
// init with the *public key*!
encrypt.init(Cipher.ENCRYPT_MODE, publicKey);
// encrypt with known character encoding, you should probably use hybrid cryptography instead 
byte[] encryptedMessage = encrypt.doFinal(msg.getBytes(StandardCharsets.UTF_8));

and decryption is:

Cipher decrypt=Cipher.getInstance("RSA/ECB/PKCS1Padding");
decrypt.init(Cipher.DECRYPT_MODE, privateKey);
String decryptedMessage = new String(decrypt.doFinal(encryptedMessage), StandardCharsets.UTF_8);