我想使用Java KeyStore庫在JKS文件中存儲多個私鑰。我創建了一個寫入和讀取JKS文件的方法,但私鑰沒有保存在文件中。KeyStore沒有保存到文件
當我將某些東西存儲到KeyStore中時,我可以獲取密鑰庫中的所有別名,並且新密鑰在那裏。一旦該方法關閉,並試圖拉同樣的鑰匙,它不會找到鑰匙。
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!
爲什麼鍵沒有被保存到JKS文件的文件?
什麼getFile2方法?你的問題中沒有這樣的方法。這個問題似乎不適合在stackoverflow,因爲它實際上不提供足夠的信息。 – eis
它在'FileInputStream'構造函數 – develop1
中的'getOrSetPrivateKey'方法中,但在何處定義? – eis