安卓密钥库错误“无法在密钥库中生成密钥”

我在尝试为某些设备生成密钥时收到错误。我能够在运行4.4.2的三星Galaxy Note上重现该错误。

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)
        at com.eric.demo.MainActivity.generateKeyPair(MainActivity.java:65)
        at com.eric.demo.MainActivity.onClickButton(MainActivity.java:43)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at android.view.View$1.onClick(View.java:3964)
        at android.view.View.performClick(View.java:4640)
        at android.view.View$PerformClick.run(View.java:19421)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5476)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
        at dalvik.system.NativeStart.main(Native Method)

我创建了一个小应用程序,仅通过从Android开发人员页面逐行复制代码来生成密钥,https://developer.android.com/training/articles/keystore.html“生成新私钥”下。

 public void onClickButton (View view) {
    try {
        generateKeyPair(this, "test3");
    } catch (Exception e){
        Log.wtf("exception", e);
    }
}

private void generateKeyPair(Context context, String alias)
    throws Exception {
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    cal.add(Calendar.YEAR, 1);
    Date end = cal.getTime();

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext())
            .setAlias(alias)
            .setStartDate(now)
            .setEndDate(end)
            .setSerialNumber(BigInteger.valueOf(1))
            .setSubject(new X500Principal("CN=test3"))
            .build());

    KeyPair kp = kpg.generateKeyPair();
}

该错误似乎发生在 AndroidKeyPairGenerator 中的 kpg.generateKeyPair() 中.java:

if (!mKeyStore.generate(privateKeyAlias, KeyStore.UID_SELF, keyType,
        mSpec.getKeySize(), mSpec.getFlags(), args)) {
    throw new IllegalStateException("could not generate key in keystore");
}

在密钥库中.java:

public boolean generate(String key, int uid, int keyType, int keySize, int flags,
        byte[][] args) {
    try {
        return mBinder.generate(key, uid, keyType, keySize, flags, args) == NO_ERROR;
    } catch (RemoteException e) {
        Log.w(TAG, "Cannot connect to keystore", e);
        return false;
    }
}

mBinder.generate() 调用似乎返回 2,这意味着密钥库已锁定?

// ResponseCodes
public static final int NO_ERROR = 1;
public static final int LOCKED = 2;
public static final int UNINITIALIZED = 3;
public static final int SYSTEM_ERROR = 4;
public static final int PROTOCOL_ERROR = 5;
public static final int PERMISSION_DENIED = 6;
public static final int KEY_NOT_FOUND = 7;
public static final int VALUE_CORRUPTED = 8;
public static final int UNDEFINED_ACTION = 9;
public static final int WRONG_PASSWORD = 10;

该错误可能与密钥库此问题 https://code.google.com/p/android/issues/detail?id=177459&q=could%20not%20generate%20key%20in%20keystore&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars

我单独尝试了一些事情以及以下组合:
1.设置加密要求。结果是另一个错误:“如果需要加密,Android 密钥库必须处于已初始化和解锁状态”
2.设置锁定屏幕(图案、PIN、无、密码、轻扫)。相同的行为
3.以编程方式尝试使用或尝试解锁凭据存储解锁或重置凭据存储会显示“输入凭据存储的密码”消息,其中没有合理的密码有效,甚至清除凭据也无济于事。startActivity(new Intent("com.android.credentials.UNLOCK"));startActivity(new Intent("com.android.credentials.RESET"));


答案 1
public class EncryptionApi18AndAbove{
    private Context context;
    private KeyStore keyStore;
    private static String alias = "alias";

    public EncryptionApi18AndAbove(Context context) {
        this.context = context;
        try {
            keyStore = KeyStore.getInstance("AndroidKeyStore");
            keyStore.load(null);
        } catch (Exception e) {
           // bla bla
        }
    }

    private String createNewKeys(String alias, Context context) {
        try {
            if (!keyStore.containsAlias(alias)) {
                Calendar start = Calendar.getInstance();
                Calendar end = Calendar.getInstance();
                end.add(Calendar.YEAR, 1);
                KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                        .setAlias(alias)
                        .setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                        .setSerialNumber(BigInteger.ONE)
                        .setStartDate(start.getTime())
                        .setEndDate(end.getTime())
                        .build();
                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
                generator.initialize(spec);
                generator.initialize(spec);
                generator.generateKeyPair();
            }
        } catch (Exception e) {
            //bla bla
        }
        return alias;
    }

    @Override
    public String encrypt(String text) {
        if (text == null || text.length() == 0) {
            return text;
        }
        try {
            KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(createNewKeys(alias, context), null);
            PublicKey publicKey = privateKeyEntry.getCertificate().getPublicKey();
            Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            inCipher.init(Cipher.ENCRYPT_MODE, publicKey);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            CipherOutputStream cipherOutputStream = new CipherOutputStream(
                    outputStream, inCipher);
            cipherOutputStream.write(text.getBytes("UTF-8"));
            cipherOutputStream.close();

            return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
        } catch (Exception e) {
            //bla bla
        }
        return text;
    }

    @Override
    public String decrypt(String text) {
        if (text == null || text.length() == 0) {
            return text;
        }
        try {
            KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(createNewKeys(alias, context), null);
            PrivateKey privateKey = privateKeyEntry.getPrivateKey();

            Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            output.init(Cipher.DECRYPT_MODE, privateKey);

            CipherInputStream cipherInputStream = new CipherInputStream(
                    new ByteArrayInputStream(Base64.decode(text, Base64.DEFAULT)), output);
            ArrayList<Byte> values = new ArrayList<>();
            int nextByte;
            while ((nextByte = cipherInputStream.read()) != -1) {
                values.add((byte) nextByte);
            }
            byte[] bytes = new byte[values.size()];
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = values.get(i).byteValue();
            }
            return new String(bytes, 0, bytes.length, "UTF-8");

        } catch (Exception e) {
            // bla bla
        }
        return text;
    }
}

您可以使用此类 。这是工作最低 SDK 18 及更高版本。您可以创建 Android 密钥库密钥 ,解密和加密简单的文本。


答案 2

虽然我不知道完整的答案,但我可以帮助你继续搜索。mBinder 另一端的绑定器实现是本机密钥库。如果我完全记得,它的行为是1)在软件级别支持密钥操作,或者2)委托给OEM提供的keymaster库,该库(可能)连接到OEM的硬件支持的密钥库。有关此内容的更多信息,请单击此处此处此处

注意:我将放弃SO将外部链接内容拉入答案的正常政策,因为我将您链接到三篇>1页面的文章,并且发布6页的答案似乎有点荒谬;-)


推荐