Search code examples
androidencryptionaeskeystore

Android KeyStore: Unsupported secret key algorithm: AES/CBC/PKCS5Padding


I am trying to store an AES key in the Android KeyStore using following code:

SecretKey AESkey = new SecretKeySpec(
  byteKey, 0, byteKey.length, "AES/CBC/PKCS5Padding");  

if (ks == null) 
{
  ks = KeyStore.getInstance("AndroidKeyStore");
  ks.load(null);
}

ks.deleteEntry("aes_key");
ks.setEntry("aes_key",
   new KeyStore.SecretKeyEntry(AESkey),
   new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT |
         KeyProperties.PURPOSE_DECRYPT)
         .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
         .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
         .build());

The line with 'setEntry(...)' fails throwig:

java.security.KeyStoreException: java.lang.IllegalArgumentException: Unsupported secret key algorithm: AES/CBC/PKCS5Padding

How can I store my key in the Android.KeyStore?


Solution

  • CBC and PKCS5Padding are not part of a key but key size is.

    Somewhat guessing given the error message just use "AES".

    SecretKey AESkey = new SecretKeySpec(byteKey, 0, byteKey.length, "AES");  
    

    The documentation is thin at best and the closest I can find is SecretKeyFactory Algorithms: "AES" Constructs secret keys for use with the AES algorithm. See: SecretKeyFactory Algorithms.