在AndroidKeystore中保存并检索KeyPair

时间:2017-02-08 10:08:34

标签: android rsa android-keystore

我需要生成一个RSA 2018 Keypair,然后保存它,如果存在则恢复。

此刻,我有这个:

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;
            }
        }

但是工作不正常,因为在应用程序的第二次运行时,密钥库不包含Keypair。

https://developer.android.com/training/articles/keystore.html?hl=es中,我看到KeyGenParameterSpec,构建者有一个"别名"价值,但在RSAKeyGenParameterSpec不是。{

如何保存?

2 个答案:

答案 0 :(得分:4)

需要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();

答案 1 :(得分:-1)

另外为 SDK <= 22 回答 pedrofb ,您可以使用KeyPairGeneratorSpec代替KeyGenParameterSpec

  

信息:   https://developer.android.com/reference/android/security/KeyPairGeneratorSpec.html