I am using AES encryption and decryption using java. And I use Appache commons library for conversion from string to byte and vice versa. But when I decrypt data then it is different from the input data that was encrypted using same key? why is so
Here is my code:
public static void main(String[] args) throws Exception {
String key="this is key";
String message="This is just an example";
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(Base64.decodeBase64(key)));
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted= cipher.doFinal(Base64.decodeBase64(message));
String encryptedString=Base64.encodeBase64String(encrypted);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original =
cipher.doFinal(Base64.decodeBase64(encryptedString));
System.out.println(Base64.encodeBase64String(original));
}
I get the output “Thisisjustanexamplc=” where it should have been “This is just an example”. what I need to change in my code. Thanks in advance
You are base-64–decoding your plain text message. You should use
message.getBytes(StandardCharsets.UTF_8)(or some other encoding) to convert to bytes instead. Base-64 encode the result of the encryption operation, then base-64 decode it before decrypting. Usenew String(original, StandardCharsets.UTF_8)to convert the result of the decryption operation back to text.In other words, use a character encoding to convert between text and bytes. Use base-64 encoding and decoding to encode binary data in a text form.