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

1

8

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.

Veiling answered 12/12, 2011 at 21:11 Comment(4)
RSA is non-determinstic.Gat
@SLaks: Do you want to post it as an answer? It's correct :D I'll give 35 rep points.Veiling
Actually, 15; I hit the rep limit long ago. :)Gat
See also #5488901Gat
G
7

RSA is non-determinstic.

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

Gat answered 19/12, 2011 at 21:28 Comment(1)
Don't bother; I generally hit the rep limit every weekday.Gat

© 2022 - 2024 — McMap. All rights reserved.