Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aramezx/7a9ae46fa02dc1875b311323ef68abab to your computer and use it in GitHub Desktop.
Save aramezx/7a9ae46fa02dc1875b311323ef68abab to your computer and use it in GitHub Desktop.
Here's how generating and retrieving a 256-bit AES key looks when using the new M APIs:
/*
* Android M officially introduces several new keystore features into the framework API,
* but the underlying work to support them has been going on for quite a while in the AOSP master branch.
* The most visible new feature is support for generating and using symmetric keys that
* are protected by the system keystore. Storing symmetric keys has been possible in previous versions too,
* but required using private (hidden) keystore APIs, and was thus not guaranteed to be portable across versions.
* Android M introduces a keystore-backed symmetric KeyGenerator, and adds support for the KeyStore.SecretKeyEntry JCA class,
* which allows storing and retrieving symmetric keys via the standard java.security.
* KeyStore JCA API. To support this, Android-specific key parameter classes and associated builders
* have been added to the Android SDK.
*/
// Here's how generating and retrieving a 256-bit AES key looks when using the new M APIs:
// key generation
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder("key1",
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
KeyGenParameterSpec keySpec = builder
.setKeySize(256)
.setBlockModes("CBC")
.setEncryptionPaddings("PKCS7Padding")
.setRandomizedEncryptionRequired(true)
.setUserAuthenticationRequired(true)
.setUserAuthenticationValidityDurationSeconds(5 * 60)
.build();
KeyGenerator kg = KeyGenerator.getInstance("AES", "AndroidKeyStore");
kg.init(keySpec);
SecretKey key = kg.generateKey();
// key retrieval
KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry("key1", null);
key = entry.getSecretKey();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment