Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encryption and decryption with private key in Java

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);
like image 882
Nadendla Avatar asked May 23 '14 13:05

Nadendla


1 Answers

How Public Private Key Encryption is working:

  1. IF you encrypt something with your private key anyone with your public key can decrypt it.
  2. IF you encrypt something with your public key only your private key can decrypt it.

You have to generate public private key pair. Private key is just for you and public key can be given to people you trust.

How to generate key pairs?

$ openssl genrsa -out private_key.pem 1024
$ openssl rsa -pubout -in private_key.pem -out public_key.pem

Or go here in do it in java -> JAVA RSA When you do that come back and ask more questions

like image 76
dharr Avatar answered Oct 19 '22 17:10

dharr