我有以下setKey()
:
try {
if(keyPair!=null) {
privateKeyResult = (RSAKey) keyPair.getPrivate();
certificate = generateCertificate(keyPair, before, after);
}
} catch (NoSuchAlgorithmException | CertificateEncodingException | InvalidKeyException | NoSuchProviderException | SignatureException e) {
logger.error("Error in preparing for insertion to keystore", e);
sendLogs(e);
}
try {
if(keyStore!=null) {
keyStore.setKeyEntry(alias, (Key) privateKeyResult, null, new Certificate[]{certificate});
}
} catch (KeyStoreException e) {
logger.error("Error in insertion to keystore", e);
sendLogs(e);
}
以及以下getKey():
try {
privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
if (privateKeyEntry == null) {
if (createKeyIfNotExists) {
logger.info("key is null, will attempt to create a new one");
setKey(alias,null);
//get the newly create key
privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
}
} else {
//logger.debug("key was found");
privateKey = (RSAKey) privateKeyEntry.getPrivateKey();
return privateKey;
}
} catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException | NullPointerException e) {
logger.error("Exception getting key from keystore", e);
sendLogs(e);
}
虽然它可以在99.98%的设备上运行,但仍有一些设备(主要是OnePlus),我有以下例外:
java.security.KeyStore$TrustedCertificateEntry cannot be cast to java.security.KeyStore$PrivateKeyEntry
在尝试获取privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
时,在PrivateKeyEntry
行中。我究竟做错了什么?如何解决此问题以确保应用程序在100%设备上运行?谢谢。
答案 0 :(得分:0)
可能在OnePlus中,getEntry
仅返回密钥对条目的Certificate
。
你可以做这样的事情来相应地施展它:
KeyStore.Entry entry = ks.getEntry("ALIAS", new KeyStore.PasswordProtection("PASSWORD".toCharArray()));
if (entry instanceof KeyStore.PrivateKeyEntry)
System.out.println("Private Key...");
else if (entry instanceof KeyStore.TrustedCertificateEntry)
System.out.println("Trusted Certificate...");
else if (entry instanceof KeyStore.SecretKeyEntry)
System.out.println("Secret Key...");