KeyPairGenerator.generateKeyPair () on Android 7.1.1

We saw an influx of the following exceptions and only for Android 7.1.1 (API 25). Has something changed in 7.1.1 to prevent this from happening?

java.security.ProviderException: Failed to load generated key pair from keystore
    at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:518)
    at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:470)

Sanitized code below (may have minor errors in the copy folder)

 KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    String certInfo = String.format(Locale.ROOT, "CN=%s, OU=%s", new Object[]{"KeyName", context.getPackageName()});
  generator.initialize(new KeyPairGeneratorSpec.Builder(context)).setAlias("KeyName").setSubject(new X500Principal(certInfo)).setSerialNumber(BigInteger.ONE).setStartDate(start).setEndDate(end).build());
  generator.generateKeyPair();
+4
source share
1 answer

I saw this error before and most likely caused by the fact that KeyPairGeneratorSpec , for API> 23 you should use KeyGenParameterSpec .

If you focus on the API below 23, I suggest you use some kind of mechanism to use different specifications depending on the level of the API.

AlgorithmParameterSpec spec;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
    spec = new KeyGenParameterSpec.Builder(KEY_ALIAS, purposes)
                 .setCertificateSubject(new X500Principal("CN=" + KEY_ALIAS))
                 .setCertificateSerialNumber(BigInteger.TEN)
                 .setCertificateNotBefore(start.getTime())
                 .setCertificateNotAfter(end.getTime())
                 .build();
} else {
    spec = new KeyPairGeneratorSpec.Builder(Application.getApp().getApplicationContext())
                 .setAlias(KEY_ALIAS)
                 .setSubject(new X500Principal("CN=" + KEY_ALIAS))
                 .setSerialNumber(BigInteger.TEN)
                 .setStartDate(start.getTime())
                 .setEndDate(end.getTime())
                 .build();
}
KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA, AndroidKeyStore);
kpg.initialize(spec);
kpg.generateKeyPair();

, , Android, API > 23, .

SO .

+1

Source: https://habr.com/ru/post/1667584/


All Articles