我正在尝试以编程方式在Java中创建一个新的密钥库。以下代码:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.setCertificateEntry("alias", cert);
抛出未初始化的KeyStore异常。
答案 0 :(得分:68)
要在Java中创建新的KeyStore,首先需要创建KeyStore文件,然后使用store(FileOutputStream, char[])
方法存储它:
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] password = "some password".toCharArray();
ks.load(null, password);
// Store away the keystore.
FileOutputStream fos = new FileOutputStream("newKeyStoreFileName");
ks.store(fos, password);
fos.close();
我希望这会有所帮助,您可以看到更多信息here。
答案 1 :(得分:51)
KeyStore需要在创建后加载。 load方法要求FileInputStream读取,但如果提供null,则加载空的KeyStore。
请参阅this link
答案 2 :(得分:4)
我使用此代码,它有效,希望它可以提供帮助。
public static KeyStore createKeyStore() throws Exception {
File file = new File("/Users/keyserverstore.keystore");
KeyStore keyStore = KeyStore.getInstance("JKS");
if (file.exists()) {
// if exists, load
keyStore.load(new FileInputStream(file), "123456".toCharArray());
} else {
// if not exists, create
keyStore.load(null, null);
keyStore.store(new FileOutputStream(file), "123456".toCharArray());
}
return keyStore;
}
答案 3 :(得分:0)
// load the keystore
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(new FileInputStream("KEYSTORE.p12"), "passwd".toCharArray());
// load the private key entry from the keystore
Key key = p12.getKey("mykey", "passwd".toCharArray());
PrivateKey privKey = (PrivateKey) key;
答案 4 :(得分:-9)
public static void main(String[] args) {
// Load the JDK's cacerts keystore file
String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar);
FileInputStream is = new FileInputStream(filename);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
char[] password = "changeit".toCharArray();
//keystore.load(is, password.toCharArray());
keystore.load(is, password);
// This class retrieves the most-trusted CAs from the keystore
PKIXParameters params = new PKIXParameters(keystore);
// Get the set of trust anchors, which contain the most-trusted CA certificates
java.security.cert.Certificate sapcert = keystore.getCertificate("SAPNetCA");
PublicKey sapcertKey = sapcert.getPublicKey();
System.out.println(sapcertKey);
Enumeration<String> aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
//System.out.println("alias certificates :"+alias);
if (keystore.isKeyEntry(alias)) {
keystore.getKey(alias, password);
}
}