Shu*_*udy 5 android rsa android-keystore
我需要生成一个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();
Run Code Online (Sandbox Code Playgroud)
效果很好,但是现在我尝试从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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是无法正常工作,因为在应用程序的第二次运行中,密钥库不包含密钥对。
在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();
Run Code Online (Sandbox Code Playgroud)
加载密钥
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5134 次 |
| 最近记录: |