【问题标题】:KeyStore.getCertificate() floods the log with warningsKeyStore.getCertificate() 用警告淹没日志
【发布时间】:2020-06-29 07:24:40
【问题描述】:

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

val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
if (keyStore.getCertificate("foobar") == null) {
     Log.d("kkkkk", "keystore not found")
}

每次我调用 getCertificate() 方法时,KeyStore 都会将堆栈跟踪作为警告放入日志中。尽管代码按预期工作,但仍然非常令人沮丧,因为我们非常广泛地使用此功能并且我们的日志变得非常难以阅读。我几乎在所有至少运行 Android 9 的手机上都遇到过这种情况。这是堆栈跟踪的开头:

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)

经过一番搜索,我发现了许多类似的问题,但大多数人都推荐这个解决方案来解决问题,比如this one

你能推荐一些东西来消除这些警告吗?

【问题讨论】:

    标签: android android-keystore


    【解决方案1】:

    感谢这个问题!如果可能,您应该将自己的问题标记为已接受的答案。

    我遇到了同样的问题,并按照您提供的链接进行操作。在the answer from NullPointer(比你的问题更早)里面,有这句话帮助我弄清楚发生了什么:

    这意味着,没有私钥,您应该先创建并存储一个密钥对,然后再在密钥库中搜索它。

    换个说法:如果您搜索一个不存在的证书,您将看到这个烦人的日志。 您应该首先查找私钥(使用 keyStore.getKey),如果存在,您可以查找证书。

    要重写它,它可能看起来像这样:

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

    【讨论】:

    • 嗨,mgueydan!抱歉反应迟了!所以实际应用程序中的实现要复杂得多,但我已经检查过了,证书永远不会为空(否则应用程序会崩溃),我们总是在使用 keyStore.containsAlias 调用 getCertificate() 之前检查别名的存在() 方法。但是,我看到在某些情况下,私钥实际上是空的。所以我一定会照顾这怎么可能。谢谢你的想法!
    • 顺便说一句,我向 Google 提交了一个错误。 issuetracker.google.com/issues/152844288
    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 2020-12-16
    • 2013-02-25
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多