gpt4 book ai didi

Java RSA 加密不可重复?

转载 作者:行者123 更新时间:2023-12-01 07:15:05 26 4
gpt4 key购买 nike

我在使用 RSA 公钥加密时遇到了问题。以下是重现该问题的示例 JUnit 代码:

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);
}
}

结果呢?断言失败。

为什么会出现这种行为?据我记得我的加密类(class),任何 key 都可以用于加密。然而,这并不是这里发生的事情。我用私钥测试了同样的事情,并且得到了可重复的输出。

如果由于某种原因,禁止使用公钥进行 RSA 加密,那么为什么我没有得到异常(exception)?

我必须做什么才能获得可重复的结果?

附注我的 JDK 是 1.6.0_22,在 Ubuntu 10.10 机器上运行。

最佳答案

我的猜测是,它正在应用随机填充,正是为了使其更安全。来自 RSA wikipedia page :

Because RSA encryption is a deterministic encryption algorithm – i.e., has no random component – an attacker can successfully launch a chosen plaintext attack against the cryptosystem, by encrypting likely plaintexts under the public key and test if they are equal to the ciphertext. A cryptosystem is called semantically secure if an attacker cannot distinguish two encryptions from each other even if the attacker knows (or has chosen) the corresponding plaintexts. As described above, RSA without padding is not semantically secure.

...

To avoid these problems, practical RSA implementations typically embed some form of structured, randomized padding into the value m before encrypting it. This padding ensures that m does not fall into the range of insecure plaintexts, and that a given message, once padded, will encrypt to one of a large number of different possible ciphertexts.

关于Java RSA 加密不可重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4758321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com