无法在Android密钥库中生成密钥

Fre*_*yhr 22 java security android keystore android-keystore

我们目前遇到的问题是,当用户安装我们的应用程序时,应用程序会尝试访问并在密钥库中生成密钥,但密钥库会抛出此异常:

Caused by: java.lang.IllegalStateException: could not generate key in keystore
        at android.security.AndroidKeyPairGenerator.generateKeyPair(AndroidKeyPairGenerator.java:100)
        at java.security.KeyPairGenerator$KeyPairGeneratorImpl.generateKeyPair(KeyPairGenerator.java:275)
Run Code Online (Sandbox Code Playgroud)

我们认为它与手机上的解锁模式有关,无法解锁密钥库,和/或设备管理员锁定密钥库.

这是密钥库的创建方式以及密钥的生成方式:

public SecretKeyWrapper(Context context, String alias) throws GeneralSecurityException, IOException {
    mCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);

    if (!keyStore.containsAlias(alias)) {
        generateKeyPair(context, alias);
    }

    final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
    mPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
}

private static void generateKeyPair(Context context, String alias) throws GeneralSecurityException {
    final Calendar start = new GregorianCalendar();
    final Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 100);

    final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
            .setAlias(alias)
            .setSubject(new X500Principal("CN=" + alias))
            .setSerialNumber(BigInteger.ONE)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();

    final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    gen.initialize(spec);
    gen.generateKeyPair();
}
Run Code Online (Sandbox Code Playgroud)

有谁知道如何:

  • 将密钥库锁定为设备管理员?
  • 密钥库在被设备管理员锁定后解锁?
  • 或者以另一种方式重现这个问题?

Jam*_*mim 11

Caused by: java.lang.IllegalStateException: could not generate key in keystore

希望第一个例外将通过以下代码解决:

KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.Entry entry = ks.getEntry(alias, null);

ks.getEntry(alias, new KeyStore.PasswordProtection(password))
Run Code Online (Sandbox Code Playgroud)

当密钥库被设备管理员锁定时解锁密钥库:

KeyStore不仅可以锁定在预ICS设备上.KeyStore锁定最简单的方法是:

  1. 通过设置KeyGuard(屏幕锁定上的图案,图钉或密码)来初始化KeyStore
  2. 添加密钥或您在KeyStore中存储的任何内容
  3. 转到设置>安全性并将屏幕锁定更改为"不安全",例如,幻灯片.
  4. 重启设备.

设备启动后,KeyStore将被锁定.com.android.credentials.UNLOCKintent将启动com.android.settings.CredentialStorage活动,反过来,它将显示UnlockDialog,提示输入密码.

 * KeyStore: LOCKED
 * KeyGuard: OFF/ON
 * Action:   old unlock dialog
 * Notes:    assume old password, need to use it to unlock.
 *           if unlock, ensure key guard before install.
 *           if reset, treat as UNINITALIZED/OFF
Run Code Online (Sandbox Code Playgroud)

您只需生成一个主密钥并将其存储为私有文件,其他应用程序将无法读取它,因此您可以在非root设备上使用它.这是在Android开发者博客上推荐的方法:: http://android-developers.blogspot.jp/2013/02/using-cryptography-to-store-credentials.html