gpt4 book ai didi

java - keystore 未保存到文件

转载 作者:行者123 更新时间:2023-12-02 02:41:12 25 4
gpt4 key购买 nike

我正在尝试使用 Java KeyStore 库将多个私钥存储在 JKS 文件中。我创建了一种写入和读取 JKS 文件的方法,但私钥未保存在文件中。

当我将某些内容存储到 keystore 中时,我可以获得 keystore 中的所有别名,并且新 key 就在那里。一旦该方法关闭并尝试拉动相同的 key ,它就找不到该 key 。

Main.java

public static void main(String[] args) throws Exception {
//Create keys
main m = new main();
m.getOrSetPrivateKey("123", "123", privateKey, false);

PrivateKey p = m.getOrSetPrivateKey("123", "123", null, true);

if (p.equals(c.getPriv_key()))
System.err.println("Equal");
else
System.err.println("Not equal !!!!!!!!");

}


private synchronized PrivateKey getOrSetPrivateKey(String alias, String id, PrivateKey c, boolean read ) throws InterruptedException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, InvalidKeySpecException, NotSupportedException, UnrecoverableKeyException {
PrivateKey key = null;

InputStream inpusStream = new FileInputStream(getFile2(Constants.JKS_PRIVATE_FILE_NAME));
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(inpusStream, Constants.JKS_PRIVATE_FILE_PASSWORD);
} finally {
if (inpusStream != null)
inpusStream.close();
}
Enumeration<String> s = keyStore.aliases();

while (s.hasMoreElements())
System.err.println("[ " + s.nextElement() + " ]");

//Generate password for this private key
char [] pass = getKeyPassword(c, alias, id);


if (read == true) { //If reading/getting private key from file store
boolean isKeyEntry = keyStore.isKeyEntry(alias);//Check if there is a key with the alias deviceSerialnumber
if (!isKeyEntry) {//No key with this alias exists
throw new KeyStoreException("No key with alias " + alias + " exists!");
}

key = (PrivateKey) keyStore.getKey(alias, pass);

} else { //Writing/ saving key to the file store
keyStore.setKeyEntry(alias, c , pass, new Certificate[] { createCertificate() });
FileOutputStream out = new FileOutputStream(new File(Constants.JKS_PRIVATE_FILE_NAME), true);
try {
keyStore.store(out, pass);

System.out.println("Alias exists = " + keyStore.containsAlias(alias));
} finally {
if (out != null)
out.close();
}
}

s = keyStore.aliases();

while (s.hasMoreElements())
System.err.println("( " + s.nextElement() + " )");

return key;
}

输出:

[ mykey ]
( 123 )
( mykey )
Alias exists = true
[ mykey ]
Exception in thread "main" java.security.KeyStoreException: No key with alias 123 exists!

为什么 key 没有保存到 JKS 文件中?

最佳答案

您将追加到现有 keystore 而不是替换它,因为您将“true”传递给 FileOutputStream 构造函数。

FileOutputStream out = new FileOutputStream(new File(Constants.JKS_PRIVATE_FILE_NAME), true);

将上面的行替换为以下内容:

FileOutputStream out = new FileOutputStream(new File(Constants.JKS_PRIVATE_FILE_NAME));

关于java - keystore 未保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45420848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com