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

Martijn Courteaux picture Martijn Courteaux · Dec 12, 2011 · Viewed 8.5k times · Source

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.

Answer

SLaks picture SLaks · Dec 19, 2011

RSA is non-determinstic.

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