Android KeyStore.getCertificate()会在日志中充满警告

Android KeyStore.getCertificate()会在日志中充满警告,android,android-keystore,Android,Android Keystore,下面是一个非常简单的示例代码: val keyStore = KeyStore.getInstance("AndroidKeyStore") keyStore.load(null) if (keyStore.getCertificate("foobar") == null) { Log.d("kkkkk", "keystore not found") } 每次调用getCertificate()方法时,密钥库都会在日志中放入一个stacktrace作为警告。尽管代码按预期工作,但它仍

下面是一个非常简单的示例代码:

val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
if (keyStore.getCertificate("foobar") == null) {
     Log.d("kkkkk", "keystore not found")
}
每次调用getCertificate()方法时,密钥库都会在日志中放入一个stacktrace作为警告。尽管代码按预期工作,但它仍然非常令人沮丧,因为我们非常广泛地使用这个函数,而且我们的日志变得很难阅读。我在几乎所有运行最少Android 9的手机上都体验到了这一点。以下是stacktrace的开始:

2020-03-27 14:34:49.541 26536-26536/com.example.keystoreexceptiontest W/KeyStore: KeyStore exception
    android.os.ServiceSpecificException:  (code 7)
        at android.os.Parcel.createException(Parcel.java:2085)
        at android.os.Parcel.readException(Parcel.java:2039)
        at android.os.Parcel.readException(Parcel.java:1987)
        at android.security.keystore.IKeystoreService$Stub$Proxy.get(IKeystoreService.java:978)
        at android.security.KeyStore.get(KeyStore.java:236)
        at android.security.KeyStore.get(KeyStore.java:225)
        at android.security.keystore.AndroidKeyStoreSpi.engineGetCertificate(AndroidKeyStoreSpi.java:160)
        at java.security.KeyStore.getCertificate(KeyStore.java:1120)
经过一番搜索,我发现了许多类似的问题,但大多数问题都建议使用此解决方案来解决问题,如


你能推荐一些方法来消除这些警告吗?

谢谢你的提问!如果可能的话,你应该把你自己的问题标记为被接受的答案

我也有同样的问题,并遵循了您提供的链接。里面(比你的问题还要古老)有一句话帮助我弄清楚发生了什么:

这意味着,没有私钥,在密钥存储中搜索密钥对之前,应该首先创建并存储密钥对

换言之:如果你搜索一个不存在的证书,你会有这个恼人的日志。 您应该首先查找私钥(使用keyStore.getKey),如果它存在,您可以查找证书

要重写它,它可能如下所示:

val privateKey = keyStore.getKey(keyAlias,null);
if (privateKey != null) {
    publicKey = keyStore.getCertificate(keyAlias)?.publicKey;
}
else
{
    createKey();
}

嗨,米盖丹!抱歉反应太晚了!因此,实际应用程序中的实现要复杂得多,但我已经检查了它,并且证书从不为null(否则应用程序将崩溃),我们总是在使用keyStore.containsAlias()方法调用getCertificate()之前检查别名的存在性。但是,我发现在某些情况下私钥实际上是空的。所以我一定会考虑这是怎么可能的。谢谢你的主意!顺便说一句,我向谷歌提交了一个bug。