Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA Encryption with given public key (in Java)

I'm looking for a Java sample how to do RSA Encryption with a given public key (I have it in base64 format, seems it is 1024 bit length).

Below is my code, but I have InvalidKeySpec exception.

String publicKey = "AJOnAeTfeU4K+do5QdBM2BQUhfrRI2rYf/Gk4a3jZJB2ewekgq2VgLNislBdql/glA39w0NjXZyTg0mW917JdUlHqKoQ9765pJc4aTjvX+3IxdFhteyO2jE3vKX1GgA3i3n6+sMBAJiT3ax57i68mbT+KAeP1AX9199aj2W4JZeP"; KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] res = new Base64Encoder().decode(publicKey.getBytes()); X509EncodedKeySpec KeySpec = new X509EncodedKeySpec(res); RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(KeySpec);  // here the exception occurs..  Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherData = cipher.doFinal(input.getBytes()); return cipherData; 

Please give me the sample,

like image 647
david.papirov Avatar asked Apr 26 '11 11:04

david.papirov


People also ask

Can you encrypt with RSA public key?

RSA(Rivest-Shamir-Adleman) is an Asymmetric encryption technique that uses two different keys as public and private keys to perform the encryption and decryption. With RSA, you can encrypt sensitive information with a public key and a matching private key is used to decrypt the encrypted message.

Can you decrypt RSA with public key?

Once the sender has the public key of their recipient, they can use it to encrypt the data that they want to keep secure. Once it has been encrypted with a public key, it can only be decrypted by the private key from the same key pair. Even the same public key can't be used to decrypt the data.


1 Answers

Here's how I manage to encrypt a string with only a RSA public key.

First save the public key in PEM-format to the filename pubkey.pem

-----BEGIN PUBLIC KEY----- AJOnAeTfeU4K+do5QdBM2BQUhfrRI2rYf/Gk4... -----END PUBLIC KEY----- 

Find the public RSA key modulus

$ openssl rsa -pubin -in pubkey.pem -modulus -noout Modulus=F56D... 

Find the public RSA key Exponent

$ openssl rsa -pubin -in pubkey.pem -text -noout ... Exponent: 65537 (0x10001) 

Then insert them into the following code.

BigInteger modulus = new BigInteger("F56D...", 16); BigInteger pubExp = new BigInteger("010001", 16);  KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp); RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);  Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key);  byte[] cipherData = cipher.doFinal(text.getBytes()); 
like image 126
nevcx Avatar answered Oct 13 '22 00:10

nevcx