Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to create a RSA Public Key from the String

I have the byte array of the RSA Public Key. I found on the internet that I can create a real PublicKey object of it by using this code:

PublicKey publicKey = 
    KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));

But every time I run this code, I'm getting another result for the encrypted data using that key. I'm sure the data I want to encrypt is always the same, so does the byte array representing the key.

Is this normal?

Here is my code always producing another output:

byte[] keyBytes = Base64.decodeBase64(rsa_1024_public_key);
      // rsa_1024_public key is a constant String

Cipher c = Cipher.getInstance("RSA");

PublicKey publicKey =
   KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes));

c.init(Cipher.ENCRYPT_MODE, publicKey);

return c.doFinal(password.getBytes());

This is probably a part of the asymmetric encryption algorithm?

Thanks.

like image 666
Martijn Courteaux Avatar asked Dec 12 '11 21:12

Martijn Courteaux


1 Answers

RSA is non-determinstic.

You can make it deterministic by selecting a non-random padding mode; however, that will not be secure.

like image 149
SLaks Avatar answered Sep 20 '22 07:09

SLaks