I am trying 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, 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.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 just fine (ALGORITHM is "RSA"), when trying to decrypt the string I have just gotten from encrypting "test", I get following exception:
javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes
Should I split the encrypted bytes in chunks of 256 in order to be able to decrypt it?
RSA, or in other words Rivest–Shamir–Adleman, is an asymmetric cryptographic algorithm. It differs from symmetric algorithms like DES or AES by having two keys. A public key that we can share with anyone is used to encrypt data. And a private one that we keep only for ourselves and it's used for decrypting the data.
The problem with RSA is that as these keys get longer, the increase in security isn't commensurate to the increase in computational power it takes to use them. It's just not sustainable.
The Advance Encryption Standard (AES) cipher text method is a more accurate and elegant cryptographic method. According to testing results and the text files used, it has been concluded that the AES algorithm outperforms the Data Encryption Standard (DES) and RSA algorithms [6,7].
You can't reliably convert random bytes to a String
. The results will depend on what your default character encoding is on the machine where you run this. With many encodings, the cipher text will be corrupted, and information will be lost.
Modify your code to use a byte[]
instead (the result of the 'doFinal()` method.
If you need to convert the byte[]
to a character string, use an encoding like Base-64.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With