从AndroidKeyStore生成SecretKey

时间:2016-10-10 14:20:39

标签: android encryption android-keystore secret-key

根据此sample,我试图从SecretKey获取AndroidKeyStore

KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null);

但我得到了这个例外:

android.security.keystore.AndroidKeyStoreRSAPrivateKey cannot be cast to javax.crypto.SecretKey

这就是我创建密钥的方式:

KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(KEY_NAME)
                    .setSubject(new X500Principal("CN=" + KEY_NAME))
                    .setSerialNumber(BigInteger.valueOf(1337))
                    .setStartDate(START_TIME)
                    .setEndDate(END_TIME)
                    .build();
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");   
kpGenerator.initialize(spec);
kpGenerator.generateKeyPair();

那么有没有办法从SecretKey生成AndroidKeyStore

1 个答案:

答案 0 :(得分:1)

从Android 6.0开始,您可以使用AndroidKeystore生成AES密钥:

KeyGenerator kg = KeyGenerator.getInstance("AES", "AndroidKeyStore");
kg.init(keySpec);
SecretKey key = kg.generateKey();

有关详细信息,请参阅博文Keystore redesign in Android M (由Nikolay Elenkov撰写)。