· 6 years ago · Mar 09, 2019, 05:56 AM
1/*
2* Android M officially introduces several new keystore features into the framework API,
3* but the underlying work to support them has been going on for quite a while in the AOSP master branch.
4* The most visible new feature is support for generating and using symmetric keys that
5* are protected by the system keystore. Storing symmetric keys has been possible in previous versions too,
6* but required using private (hidden) keystore APIs, and was thus not guaranteed to be portable across versions.
7* Android M introduces a keystore-backed symmetric KeyGenerator, and adds support for the KeyStore.SecretKeyEntry JCA class,
8* which allows storing and retrieving symmetric keys via the standard java.security.
9* KeyStore JCA API. To support this, Android-specific key parameter classes and associated builders
10* have been added to the Android SDK.
11*/
12// Here's how generating and retrieving a 256-bit AES key looks when using the new M APIs:
13
14// key generation
15KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder("key1",
16 KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
17KeyGenParameterSpec keySpec = builder
18 .setKeySize(256)
19 .setBlockModes("CBC")
20 .setEncryptionPaddings("PKCS7Padding")
21 .setRandomizedEncryptionRequired(true)
22 .setUserAuthenticationRequired(true)
23 .setUserAuthenticationValidityDurationSeconds(5 * 60)
24 .build();
25KeyGenerator kg = KeyGenerator.getInstance("AES", "AndroidKeyStore");
26kg.init(keySpec);
27SecretKey key = kg.generateKey();
28
29// key retrieval
30KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
31ks.load(null);
32
33KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry("key1", null);
34key = entry.getSecretKey();