在AndroidKeystore中保存和检索KeyPair
作者:互联网
我需要生成一个RSA 2018密钥对,然后将其保存并恢复(如果存在).
此刻,我有:
SecureRandom random = new SecureRandom();
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
generator.initialize(spec, random);
return generator.generateKeyPair();
效果很好,但是现在我尝试保存并从Android Keystore中获取它,但是我没有实现.我尝试过:
String alias = "TESTINGKEY";
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
if (!keyStore.containsAlias(alias)) {
SecureRandom random = new SecureRandom();
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
generator.initialize(spec, random);
return generator.generateKeyPair();
} else {
Key key = keyStore.getKey(alias, null);
if (key instanceof PrivateKey) {
Certificate cert = keyStore.getCertificate(alias);
return new KeyPair(cert.getPublicKey(), (PrivateKey) key);
} else {
return null;
}
}
但是工作不正常,因为在应用程序的第二次运行中,密钥库不包含密钥对.
在https://developer.android.com/training/articles/keystore.html?hl=es中,我看到了KeyGenParameterSpec,该构建器具有“别名”值,但int RSAKeyGenParameterSpec没有.
我该如何保存?
解决方法:
使用AndroidKeyStore需要使用KeyGenParameterSpec.Builder生成密钥.还要使用AndroidKeyStore而不是SC.您可以使用以下代码
生成密钥(Android> = 23)
KeyPairGenerator kpg = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setKeySize(keySize)
.build());
KeyPair keyPair = kpg.generateKeyPair();
加载按键
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyStore.Entry entry = keyStore.getEntry(alias, null);
PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
PublicKey publicKey = keyStore.getCertificate(alias).getPublicKey();
标签:rsa,android-keystore,android 来源: https://codeday.me/bug/20191111/2022026.html