简体   繁体   中英

How to convert decrypted BigInteger back to string?

I am working on an RSA encryption and I can properly encrypt and decrypt a BigInteger. The issue that I am having is that before the encryption I can easily convert the BigInteger back into the original string. However, after encrypting and then decrypting the string successfully back into the original BigInteger, converting the resulting BigInteger does not give the original string. The following is the code I am using...

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

My results are the following

 Original:  22405534230753928650781647905
 Hello World!
 Result:    22405534230753928650781647905
 ���$lɋ�Xİ�d��������GJ�pu-;�Ei:�r�)��Uknԫ��m�!
 #N�l3����@�:�ƂE�ۧ���$M������V{��#C@I�md�!�

Is there a reason that this BigInteger is not converting back into the string like it does before it is decrypted? Is there something that I am missing in converting the big integer back into a string?

This line:

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

should probably be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM