0

I tried all the ways to encrypt and decrypt simple data. I used so many ways to do it but always get 'BadPaddingException' error. I am checking with other codes couldn't detect anything wrong with it.

 companion object {
    fun generateSecretKey() {
        val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
        val keyGenParameterSpec = KeyGenParameterSpec.Builder(BuildConfig.KeyStore, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build()
        keyGenerator.init(keyGenParameterSpec)
        keyGenerator.generateKey()
    }
}

private fun getSecretKey(): SecretKey? {
    val keyStore = KeyStore.getInstance("AndroidKeyStore").apply {
        load(null)
    }
    val secretKeyEntry = keyStore.getEntry(BuildConfig.KeyStore, null) as KeyStore.SecretKeyEntry?

    return secretKeyEntry?.secretKey
}

private val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
fun encrypt(data: String): String {
    generateSecretKey()
    cipher.init(Cipher.ENCRYPT_MODE, getSecretKey())
    val iv = cipher.iv
    val ivString = Base64.encodeToString(iv, Base64.DEFAULT)
    val encryptedBytes = cipher.doFinal(data.toByteArray())
    val encryptedString = Base64.encodeToString(encryptedBytes, Base64.DEFAULT)

    Log.i("ENCRYPTED STRING", encryptedString)
    Log.i("IV STRING", ivString)
    return "$encryptedString]$ivString"
}

fun decrypt(data: String): String {
    val values = data.split("]".toRegex())
    val spec = IvParameterSpec(Base64.decode(values[1], Base64.DEFAULT))
    cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), spec)
    val decodedEncryption = Base64.decode(values[0], Base64.DEFAULT)

    Log.i("DECODED ENCRYPT", values[0])
    Log.i("IV STRING", values[1])
    val bytes = cipher.doFinal(decodedEncryption)
    return String(bytes)

}

Please help me, if there is something wrong. Always get this error:

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:502)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
 Caused by: javax.crypto.BadPaddingException
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:515)
    at javax.crypto.Cipher.doFinal(Cipher.java:2055)
Amrah Aziz
  • 81
  • 6
  • Your IV is problematic. See here https://stackoverflow.com/a/49340653/1820553 – kelalaka Apr 30 '21 at 13:32
  • The code runs fine on my machine in Android Studio. You may be using the methods differently than in my test. A `BadPaddingException` typically occurs when key and ciphertext do not match (because the padding after decryption is then not PKCS7 compliant). – Topaco May 01 '21 at 09:29

0 Answers0