I have a problem with RSA public key encryption. Here is a sample JUnit code that reproduces the problem:
public class CryptoTests { private static KeyPair keys; @BeforeClass public static void init() throws NoSuchAlgorithmException{ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = CryptoUtils.getSecureRandom(); keyGen.initialize(2176, random); keys = keyGen.generateKeyPair(); } @Test public void testRepeatabilityPlainRSAPublic() throws EdrmCryptoException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{ byte[] plaintext = new byte [10]; Random r = new Random(); r.nextBytes(plaintext); Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, keys.getPublic()); byte[] encrypted1 = rsa.doFinal(plaintext); rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, keys.getPublic()); byte[] encrypted2 = rsa.doFinal(plaintext); rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, keys.getPublic()); byte[] encrypted3 = rsa.doFinal(plaintext); assertArrayEquals(encrypted1, encrypted2); assertArrayEquals(encrypted1, encrypted3); } }
Result? The statement fails.
Why is this behavior observed here? As far as I remember from my cryptographic classes, any key can be used for encryption. But that is not what is happening here. I tested the same with the private key, and get repeatable output.
If, for some reason, RSA public key encryption is prohibited, then why am I not getting an exception?
What should I do to get duplicate results?
PS My JDK is 1.6.0_22 working in a Ubuntu 10.10 window.
source share