我一直遇到与RSA公钥加密问题。以下是重现问题的示例JUnit代码:Java RSA加密不可重复?
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);
}
}
结果呢?断言失败。
为什么在这里看到这种行为?据我从加密类记得,任何密钥都可以用于加密。然而,这不是这里发生的事情。 我已经用私钥测试过相同的东西,并且我得到了可重复的输出。
如果出于某种原因使用公钥禁止RSA加密,那么为什么我没有发生异常?
我必须做些什么才能获得可重复的结果?
P.S.我的JDK是1.6.0_22,在Ubuntu 10.10上运行。
P.S.我使用了BouncyCastle提供程序,现在我的测试成功了。 – malaverdiere 2011-01-21 12:09:18
测试成功是一个非常糟糕的迹象,因为RSA加密应该*随机化。使用RSA加密使用OEAP填充是非常重要的。教科书RSA和PKCS#1 v1.5填充都不安全。 – CodesInChaos 2013-01-09 11:41:39