'javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT

I'm storing AES decryption key in AndroidKeyStore to decrypt data from SQLiteDB. Unfortunately, sometimes I get this error (Any android device and any API) rarely.

I would like to know what exactly this error means. javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT.

Where I can find list of these error:*?



Solution 1:[1]

Decryption seems to work differently in Android from default Java Code in backend. In my case I was getting this error cause. Re-encoding the value of IV and SecretKey as UTF-8.

I was converting the KEY and IV like below and I was causing string to re-encoded.

val ivParameterSpec = IvParameterSpec(iv.toByteArray(charset("utf-8")))
val secretKeySpec = SecretKeySpec(key.toByteArray(charset("utf-8")), "AES")

I removed the "UTF-8" part cause it's in default converted as "UTF-8" no need to pass it again.

val ivParameterSpec = IvParameterSpec(iv.toByteArray())
val secretKeySpec = SecretKeySpec(key.toByteArray(), "AES")

(Note: Length of encryptedData is 128. IV and Key lengths are 16. Which are all divisible by 16 as algorithm needed.)

Full-code is below.

 fun decrypt(encryptedData: String, iv: String, key: String): String? {
        try {
            //IV & Key Generation
            val ivParameterSpec = IvParameterSpec(iv.toByteArray())
            val secretKeySpec = SecretKeySpec(key.toByteArray(), "AES")

            val c = Cipher.getInstance("AES/CBC/PKCS5PADDING")
            c.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)

            val decodedValue = Base64.decode(encryptedData, Base64.URL_SAFE)
            val decValue = c.doFinal(decodedValue)

            return String(decValue)

        } catch (ex: IllegalBlockSizeException) {
            println(ex.message)
        } catch (ex: BadPaddingException) {
            println(ex.message)
        } catch (ex: InvalidKeyException) {
            println(ex.message)
        } catch (ex: NoSuchAlgorithmException) {
            println(ex.message)
        } catch (ex: NoSuchPaddingException) {
            println(ex.message)
        } catch (ex: Exception) {
            println(ex.message)
        }
        return null
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 O?uzhan Y?ld?r?m