Reputation: 1015
Iam encrypting data using the following code
final SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(),
"AES");
final String myIV = "89ABCDEF01234567";
Cipher c = null;
try {
try {
c = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(
myIV.getBytes()));
byte[] encrypted = c.doFinal(msgfromEB.getBytes(),0,msgfromEB.getBytes().length);
and iam decyrpting like this
c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(
myIV.getBytes()));
byte[] decryptedBytes = c.doFinal(encrypted ,0,encrypted .length);
System.out.println("decrypted string is"+new String(decryptedBytes));
it is working iam able to encrypt and decrypt properly
But if iam converting into a string like this
String myString = new String (encrypted);
and again get the byte array like this
byte[] newbytearray = myString.getBytes();
Now iam trying to decrypt
c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(
myIV.getBytes()));
byte[] decryptedBytes = c.doFinal(newbytearray ,0,newbytearray .length);
System.out.println("decrypted string is"+new String(decryptedBytes));
now iam getting an error
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
If iam using base64 convertion it is working fine, but I don't want to do it as it increases the length. Any other alternative to over come this?
Upvotes: 1
Views: 277
Reputation: 691625
The alternative is to transfer bytes instead of Strings.
When you're doing new String(bytes)
, you're asking to use your platform's default encoding to interpret bytes and sequences of bytes as characters. The problem is that all the bytes and sequences of bytes do not represent valid characters. The algorithm is thus lossy. That's a bit like transforming a color picture to black and white, and then trying to go from black and white to color. It doesn't work. Hence the need for base64.
An additional problem is that you don't specify any explicit encoding, which means that the sender and the receiver could use different encodings if they're not on the exact same platform.
Upvotes: 1