如何将解密的 BigInteger 转换回字符串



我正在研究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: tt" + 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 不像解密之前那样转换回字符串?在将大整数转换回字符串时我缺少什么吗?

这一行:

String message = new String(enc.toByteArray());

应该是:

String message = new String(dec.toByteArray());

最新更新