java.security.UnrecoverableKeyException:无法获取有关私钥的信息

Din*_* Tw 22 java android keystore java-security private-key

我有以下几行来从Android上的密钥存储区获取私钥

KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);

// generating key pair code omitted

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) this.keyStore.getEntry("alias", null);
Run Code Online (Sandbox Code Playgroud)

一切正常,但当操作系统从Android 5.1.1升级到Android 6.0.1时,第3行将java.security.UnrecoverableKeyException: Failed to obtain information about private key首先执行.但之后它会再次正常工作.现在我的解决方法是执行该行2次.与此同时,我也想知道是否有更好的方法来避免异常.

更新

异常跟踪

W/System.err? java.security.UnrecoverableKeyException: Failed to obtain information about private key
W/System.err? at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:217)
W/System.err? at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:253)
W/System.err? at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(AndroidKeyStoreProvider.java:263)
W/System.err? at android.security.keystore.AndroidKeyStoreSpi.engineGetKey(AndroidKeyStoreSpi.java:93)
W/System.err? at java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:372)
W/System.err? at java.security.KeyStore.getEntry(KeyStore.java:645)
W/System.err? at com.example.keystoretest.MainActivity.onCreate(MainActivity.java:113)
W/System.err? at android.app.Activity.performCreate(Activity.java:6251)
W/System.err? at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
W/System.err? at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
W/System.err? at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
W/System.err? at android.app.ActivityThread.-wrap11(ActivityThread.java)
W/System.err? at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
W/System.err? at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err? at android.os.Looper.loop(Looper.java:148)
W/System.err? at android.app.ActivityThread.main(ActivityThread.java:5417)
W/System.err? at java.lang.reflect.Method.invoke(Native Method)
W/System.err? at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
W/System.err? at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
W/System.err? Caused by: android.security.KeyStoreException: Invalid key blob
W/System.err? at android.security.KeyStore.getKeyStoreException(KeyStore.java:632)
W/System.err? at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:218)
W/System.err? ... 18 more
Run Code Online (Sandbox Code Playgroud)

Sky*_*ker 9

什么时候发生此错误,为什么?

回答:加载Android密钥并从密钥库存储公共密钥时,如果状态为锁定或未初始化,则可能会发生此错误。

错误生成部分代码如下:

@NonNull
    public static AndroidKeyStorePublicKey loadAndroidKeyStorePublicKeyFromKeystore(
            @NonNull KeyStore keyStore, @NonNull String privateKeyAlias)
            throws UnrecoverableKeyException {
        KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
        int errorCode = keyStore.getKeyCharacteristics(privateKeyAlias, null,
                null, keyCharacteristics);
        if (errorCode != KeyStore.NO_ERROR) {
            throw (UnrecoverableKeyException) new UnrecoverableKeyException(
                    "Failed to obtain information about private key")
                    .initCause(KeyStore.getKeyStoreException(errorCode)); // this exception is generated
        }
        ......
        ......
        ......
    }
Run Code Online (Sandbox Code Playgroud)

KeyStore有10个响应代码。他们是

// ResponseCodes
NO_ERROR = 1;
LOCKED = 2;
UNINITIALIZED = 3;
SYSTEM_ERROR = 4;
PROTOCOL_ERROR = 5;
PERMISSION_DENIED = 6;
KEY_NOT_FOUND = 7;
VALUE_CORRUPTED = 8;
UNDEFINED_ACTION = 9;
WRONG_PASSWORD = 10;
Run Code Online (Sandbox Code Playgroud)

KeyStore具有3个状态。它们是解锁的,锁定的,未初始化的

NO_ERROR仅在状态为UNLOCKED时发生。对于您的升级情况,状态第一次为LOCKED或UNINITIALIZED,因此错误仅发生一次。

状态检查代码如下:

public State state() {
    execute('t');
    switch (mError) {
    case NO_ERROR:
        return State.UNLOCKED;
    case LOCKED:
        return State.LOCKED;
    case UNINITIALIZED:
        return State.UNINITIALIZED;
    default:
        throw new AssertionError(mError);
    }
}
Run Code Online (Sandbox Code Playgroud)

资源链接:

  1. AndroidKeyStoreProvider Java类
  2. KeyStore Java类

更新:

从您的错误日志中,现在很明显

W/System.err? Caused by: android.security.KeyStoreException: Invalid key blob
Run Code Online (Sandbox Code Playgroud)

这是当用户尝试从LOCK / UNINITIALIZED解锁时引起的主要问题。默认情况下,它被定义为30秒计时。这个问题是与API相关的实现问题。

/**
 * If the user has unlocked the device Within the last this number of seconds,
 * it can be considered as an authenticator.
 */
private static final int AUTHENTICATION_DURATION_SECONDS = 30;
Run Code Online (Sandbox Code Playgroud)

对于加密/解密,仅当用户刚刚通过设备凭据进行身份验证时,带有生成的密钥的某些数据才有效。错误发生于

// Try encrypting something, it will only work if the user authenticated within
// the last AUTHENTICATION_DURATION_SECONDS seconds.
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // error is generated from here.
Run Code Online (Sandbox Code Playgroud)

从这里抛出实际错误。您的错误是由产生的InvalidKeyException

解:

您必须InvalidKeyException从catch参数中删除该类。这样仍可以检查InvalidKeyException。检查后,您必须再次尝试使用代码,以便该问题不会立即出现,但进行2次检查可能会解决您的问题。我尚未测试代码,但应如下所示:

try {
....
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) this.keyStore.getEntry("alias", null);
....
} catch (final Exception e) {
    e.printStackTrace();
    if (e instanceof InvalidKeyException) { // bypass InvalidKeyException
        .......
        // You can again call the method and make a counter for deadlock situation or implement your own code according to your situation
        if (retry) {
            keyStore.deleteEntry(keyName);
            return getCypher(keyName, false);
        } else {
            throw e;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

资源链接:

  1. MainActivity.java
  2. android.security.KeyStoreException:无效的密钥Blob

  • 如何删除该条目然后生成一个新条目呢?如果用户拥有需要使用密钥存储区中的现有私钥还原的加密信息,该怎么办? (9认同)
  • 这个答案让我有些困惑。尚不清楚尝试两次getEntry()如何解决该问题。30秒超时与它有什么关系?另外,为什么这样做是必需的:“您必须从catch参数中删除InvalidKeyException类”。为什么不赶上特定的InvalidKeyException进行第二次尝试呢?您是否故意吞下所有其他异常,而不是重新抛出它们? (3认同)
  • 我不明白你为什么需要调用 deleteEntry (2认同)