0

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

After the code is commented.

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

newbie dev
  • 161
  • 6
  • 19

1 Answers1

1

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))
Bach Vu
  • 2,298
  • 1
  • 15
  • 19
  • The message is not displayed when the is not commented. After this line nothing executes byte[] decValue = c.doFinal(decodedValue); – newbie dev Feb 07 '19 at 08:26
  • still the same error. There seems to have problem in decrypt method . It says that it doesnot take API less than 24 or so – newbie dev Feb 07 '19 at 13:25
  • Maybe this can be useful for you https://stackoverflow.com/questions/13433529/android-4-2-broke-my-encrypt-decrypt-code-and-the-provided-solutions-dont-work – Bach Vu Feb 08 '19 at 03:09