Java RSA encryption

I tried to encode a simple string "test" back and forth

public static String encode(Key publicKey,String data) throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException,IllegalBlockSizeException,BadPaddingException {

    byte[] byteData = data.getBytes(); // convert string to byte array

    Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object
    cipher.init(Cipher.ENCRYPT_MODE,publicKey); // initialize object's mode and key

    byte[] encryptedByteData = cipher.doFinal(byteData); // use object for encryption

    return new String(encryptedByteData); // convert encrypted byte array to string and return it

}

public static String decode(Key privateKey,BadPaddingException {

    byte[] byteData = data.getBytes(); // convert string to byte array

    Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object
    cipher.init(Cipher.DECRYPT_MODE,privateKey); // initialize object's mode and key

    System.out.println(byteData.length);

    byte[] decryptedByteData = cipher.doFinal(byteData); // use object for decryption

    return new String(decryptedByteData); // convert decrypted byte array to string and return it

}

However, although the encryption works normally (algorithm is "RSA"), when I try to decrypt the string I just got from the encryption "test", I get the following exception:

Should I split the encrypted bytes in 256 blocks to decrypt?

Solution

You cannot reliably convert random bytes to strings The result will depend on the default character encoding on the machine on which you are running this operation There are many codes, the ciphertext will be destroyed and the information will be lost

Modify the code to use byte [] instead of the result of the (dofinal()) method

If you need to convert byte [] to a string, use base-64 encoding

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>