我的问题是,当我尝试创建RSA密钥对时,私钥为null,我完全不知道为什么。从屏幕最底部的日志中,我得到
获取公钥可以很好地工作,只是私钥不能,为什么?
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
String message = "Message to encrypt";
byte[] byteMessage = message.getBytes();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
Calendar calendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
endCalendar.add(Calendar.YEAR, 20);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
generator.initialize(new KeyGenParameterSpec.Builder("ssdPrivateKey", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setDigests(KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setKeySize(2048).build());
} else {
generator.initialize(new KeyPairGeneratorSpec.Builder(MainActivity.this)
.setAlias("ssdPrivateKey")
.setSerialNumber(BigInteger.ONE)
.setSubject(new X500Principal("CN=" + "ssdPrivateKey"))
.setStartDate(calendar.getTime())
.setEndDate(endCalendar.getTime())
.setKeySize(2048).build()
);
}
KeyPair keyPair = generator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] bytes = privateKey.getEncoded();
if(bytes == null) {
Log.d("EncryptionMessage", "Bytes == null");
}