public KeyPair generateKeyPair(@NonNull Context context, @NonNull String alias) {
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.YEAR, 1);
KeyPairGenerator keyPairGenerator;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
AlgorithmParameterSpec spec;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setCertificateNotBefore(startDate.getTime())
.setCertificateNotAfter(endDate.getTime())
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.build();
} else {
spec = new KeyPairGeneratorSpec.Builder(context)
.setAlias(alias)
.setSubject(new X500Principal("CN=fake"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(startDate.getTime())
.setEndDate(endDate.getTime())
.build();
}
keyPairGenerator.initialize(spec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return keyPairGenerator.generateKeyPair();
}
i know privateKey.getEncoded can be null, but how to get the privateKey base64 value?
If you were using a provider based on a hardware cryptographic device
AndroidKeyStore
it has been set up not to publish private keys outside of it. Therefore,Key.getEncoded()
on the private key might actually return null. More details here