I have the key generated as follows:
val spec = KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setRandomizedEncryptionRequired(true)
.build()
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, keyStoreAlias)
generator.init(spec)
return generator.generateKey()
I get the SecretKey like this:
val keyStore = KeyStore.getInstance(keyStoreAlias)
keyStore.load(null)
return keystore.getKey(keyAlias, null) as SecretKey
And encrypt method as follows:
fun encrypt(data: String): ByteArray {
val aesCipher = Cipher.getInstance(encryptionAlgorithm)
aesCipher.init(Cipher.ENCRYPT_MODE, getSecretKey())
val iv = aesCipher.iv
val dataAsByteArray = data.toByteArray(Charsets.UTF_8)
return aesCipher.doFinal(dataAsByteArray)
}
And encryption algorithm declared as:
private val encryptionAlgorithm = "AES/GCM/NoPadding"
I'm running this on API 27 emulator. Question is why am I getting:
2019-11-15 01:28:59.045 31896-32044/com.compass.compass.beta W/System.err: javax.crypto.IllegalBlockSizeException
2019-11-15 01:28:59.046 31896-32044/com.compass.compass.beta W/System.err: at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:519)
2019-11-15 01:28:59.046 31896-32044/com.compass.compass.beta W/System.err: at javax.crypto.Cipher.doFinal(Cipher.java:1741)
....
2019-11-15 01:28:59.047 31896-32044/com.compass.compass.beta W/System.err: Caused by: android.security.KeyStoreException: Unknown error
2019-11-15 01:28:59.047 31896-32044/com.compass.compass.beta W/System.err: at android.security.KeyStore.getKeyStoreException(KeyStore.java:697)
2019-11-15 01:28:59.047 31896-32044/com.compass.compass.beta W/System.err: at android.security.keystore.KeyStoreCryptoOperationChunkedStreamer.update(KeyStoreCryptoOperationChunkedStreamer.java:132)
2019-11-15 01:28:59.047 31896-32044/com.compass.compass.beta W/System.err: at android.security.keystore.KeyStoreCryptoOperationChunkedStreamer.doFinal(KeyStoreCryptoOperationChunkedStreamer.java:217)
2019-11-15 01:28:59.047 31896-32044/com.compass.compass.beta W/System.err: at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:506)
None of the other answer I've found so far have helped. I've tried to read through the documentation thoroughly, and I just don't understand what's the issue here. Surprisingly, all unit tests regarding this pass. These problems arise in emulator and the actual device only.
Edit with more info: I tried this same thing on android API 29 and API 27, and this seems to happen only on API 27, but in API 29.