我正在进行RSA加密,我可以正确加密和解密BigInteger。我遇到的问题是,在加密之前,我可以轻松地将BigInteger转换回原始字符串。但是,在加密然后将字符串成功解密回原始BigInteger之后,转换生成的BigInteger不会提供原始字符串。以下是我正在使用的代码......
public static void main(String args[]) {
int keySize = 2048;
BigInteger prime1 = new BigInteger(keySize / 2, 100, new SecureRandom());
BigInteger prime2 = new BigInteger(keySize / 2, 100, new SecureRandom());
BigInteger n = prime1.multiply(prime2);
BigInteger totient = prime1.subtract(BigInteger.ONE).multiply(prime2.subtract(BigInteger.ONE));
BigInteger e;
do e = new BigInteger(totient.bitLength(), new SecureRandom());
while (e.compareTo(BigInteger.ONE) <= 0 || e.compareTo(totient) >= 0 || !e.gcd(totient).equals(BigInteger.ONE));
BigInteger d = e.modInverse(totient);
String original = "Hello World!";
//convert the string into a BigInteger and display
BigInteger enc = new BigInteger(original.getBytes());
System.out.println("Original: \t" + enc.toString());
//convert the big integer to the string to display
String originalString = new String(enc.toByteArray());
System.out.println(originalString);
enc = enc.modPow(e, n);
//decrypt and display the BigInteger value
BigInteger dec = enc;
dec = dec.modPow(d, n);
System.out.println("Result: \t\t" + dec.toString());
//Convert the big integer back into a string to display
String message = new String(enc.toByteArray());
System.out.println(message);
}
我的结果如下
Original: 22405534230753928650781647905
Hello World!
Result: 22405534230753928650781647905
���$lɋ�Xİ�d��������GJ�pu-;�Ei:�r�)��Uknԫ��m�!
#N�l3����@�:�ƂE�ۧ���$M������V{��#C@I�md�!�
有没有理由说这个BigInteger没有像解密之前那样转换回字符串?在将大整数转换回字符串时,我是否缺少某些内容?
答案 0 :(得分:3)
这一行:
String message = new String(enc.toByteArray());
应该是:
String message = new String(dec.toByteArray());