代码之家  ›  专栏  ›  技术社区  ›  Ras

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

  •  0
  • Ras  · 技术社区  · 8 年前

    我正在研究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没有像解密之前那样转换回字符串,这有什么原因吗?在将大整数转换回字符串的过程中,我是否遗漏了什么?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Chai T. Rex    8 年前

    该行:

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

    可能应该是:

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