我在KeyStore上有一些问题。我向KeyStore添加了密钥,但无法从那里获取它。
我的代码:

        try
        {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(128, random);
            SecretKey key = keygen.generateKey();
            KeyStore ks = KeyStore.getInstance("UBER", "BC");
            ks.load(null, pass);
            ks.store(new FileOutputStream(path), pass);
            ks.setKeyEntry(keyName, key, pass, null);
            System.out.println(ks.containsAlias(keyName));
            key = null;
            KeyStore ks1 = KeyStore.getInstance("UBER", "BC");
            ks1.load(new FileInputStream(path), pass);
            System.out.println(ks1.containsAlias(keyName));
        }


输出为:

true
false


好像是密钥分配器,或者我不能完全加载KeyStore。在这里看到错误了吗?

最佳答案

您要在添加密钥库之前保存密钥库。交换这两行:

        ks.store(new FileOutputStream(path), pass);
        ks.setKeyEntry(keyName, key, pass, null);


因此它们是:

        ks.setKeyEntry(keyName, key, pass, null);
        ks.store(new FileOutputStream(path), pass);

关于java - 无法从KeyStore读取 key ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36372782/

10-10 23:31