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();
}
我知道privateKey.getEncoded可以为null,但是如何获取privateKey base64值?
答案 0 :(得分:0)
如果您使用的是基于硬件加密设备AndroidKeyStore
的提供程序,则已设置为不在其外部发布私钥。因此,私钥上的Key.getEncoded()
实际上可能返回null。更多详细信息here