Home:ALL Converter>Android AES encryption and decryption

Android AES encryption and decryption

Ask Time:2015-06-24T04:37:31         Author:huber.duber

Json Formatter

I have found hundreds of examples of Android AES encryption and decryption but I am unable to make them work, even the simplest. The following code does some encryption and decryption but it spits out garbage after decrypting the encrypted text. Can you please take a look and tell me where I am wrong?

Thanks

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();

Cipher cipher = Cipher.getInstance("AES");

String plainText = "This is supposed to be encrypted";
String plainKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT);

//encrypt
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
String encryptedText = Base64.encodeToString(encryptedBytes, Base64.DEFAULT);

//decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[]decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = Base64.encodeToString(decryptedBytes, Base64.DEFAULT);

Author:huber.duber,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/31013035/android-aes-encryption-and-decryption
huber.duber :

@Barend answer works:\nYour code works fine. What @greenapps said. Instead of Base64.encodeToString(..), try printing the output of new String(decryptedBytes), you'll see that it's the value you were looking for.",
2018-04-25T03:04:23
yy