Reputation: 171
I have done encryption in android with a static password i.e. "encrypt". The encryption works fine and encrypts the data. But when i try to decrypt the encrypted text it does not show. The code to decrypt is as follow.
public String decrypt(String msg, String inputPassword) throws Exception{
SecretKeySpec key= generateKey(inputPassword);
Cipher c = Cipher.getInstance(AES);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decodedValue= Base64.decode(msg, Base64.DEFAULT);
/*If this line is present the encrypted message is not seen*/
byte[] decValue = c.doFinal(Base64.decode(decodedValue,
Base64.DEFAULT));
String decryptedValue = new String(decodedValue);
String decryptedValue = new String(decValue, StandardCharsets.UTF_8);
return decryptedValue;
}
When the code (below the comment) is enabled. The message is not displayed. But when the line is commented. This is shown in the message box
This is the encrypt and key generate methods.
public String encrypt(String message, String inputPassword) throws Exception{
SecretKeySpec key = generateKey(inputPassword);
Cipher c = Cipher.getInstance(AES);
c.init(c.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(message.getBytes());
String encryptedValue = Base64.encodeToString(encVal, Base64.DEFAULT);
return encryptedValue;
}
//For generating key for encryption
public SecretKeySpec generateKey(String inputPassword) throws Exception{
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] bytes = inputPassword.getBytes("UTF-8");
digest.update(bytes, 0, bytes.length);
byte[] key = digest.digest();
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
return secretKeySpec;
}
The log is follow enter image description here
Also the API level is not maintained... I don't know where to setup this as well. enter image description here
Upvotes: 0
Views: 636
Reputation: 2348
Could you try changing this
String decryptedValue = new String(decodedValue)
to this
String decryptedValue = new String(decodedValue, StandardCharsets.UTF_8)
And for your error, try changing to this
c.doFinal(Base64.decode(decodedValue, Base64.DEFAULT))
Upvotes: 1