从理论上讲,我知道如果n=33
,e(public key)=3
和d(private key)=7
我可以使用plaintext
类BigInteger
来加密modPow(e, n)
,并且使用modPow(d,n)
解密,但解密后plaintext
与第一次不同。
这是我的代码:
public class KeyTest {
private BigInteger n = new BigInteger("33");
private BigInteger e = new BigInteger("3");
private BigInteger d = new BigInteger("7");
public static void main(String[] args) {
KeyTest test = new KeyTest();
BigInteger plaintext = new BigInteger("55");
System.out.println("Plain text: " + plaintext);
BigInteger ciphertext = test.encrypt(plaintext);
System.out.println("Ciphertext: " + ciphertext);
BigInteger decrypted = test.decrypt(ciphertext);
System.out.println("Plain text after decryption: " + decrypted);
}
public BigInteger encrypt(BigInteger plaintext) {
return plaintext.modPow(e, n);
}
public BigInteger decrypt(BigInteger ciphertext) {
return ciphertext.modPow(d, n);
}
}
输出结果为:
Plain text: 55 Ciphertext: 22 Plain text after decryption: 22
答案 0 :(得分:3)
您的明文(55
)大于模数(33
),因此您无法实际加密消息。请考虑以下略有不同的示例:
p = 11
q = 17
n = 187
phi(n) = 160
e = 3
d = 107
则e * d = 321
= 1 mod phi(n)
所以将代码更改为:
private BigInteger n = new BigInteger("187");
private BigInteger e = new BigInteger("3");
private BigInteger d = new BigInteger("107");
public static void main(String[] args) {
KeyTest test = new KeyTest();
BigInteger plaintext = new BigInteger("55");
System.out.println("Plain text: " + plaintext);
BigInteger ciphertext = test.encrypt(plaintext);
System.out.println("Ciphertext: " + ciphertext);
BigInteger decrypted = test.decrypt(ciphertext);
System.out.println("Plain text after decryption: " + decrypted);
}
public BigInteger encrypt(BigInteger plaintext) {
return plaintext.modPow(e, n);
}
public BigInteger decrypt(BigInteger ciphertext) {
return ciphertext.modPow(d, n);
}
}
输出:
Plain text: 55
Ciphertext: 132
Plain text after decryption: 55