java-如何以编程方式创建新的KeyStore?
我正在尝试以编程方式在Java中创建新的密钥库。 如下代码:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.setCertificateEntry("alias", cert);
引发未初始化的KeyStore异常。
Καrτhικ asked 2020-01-03T16:27:09Z
5个解决方案
69 votes
要使用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();
希望对您有所帮助,您可以在此处查看更多信息。
Assaf Gamliel answered 2020-01-03T16:27:57Z
53 votes
密钥库创建后需要加载。 load方法要求读取FileInputStream,但是如果您提供的是null,则将加载一个空的KeyStore。
看到这个链接
charisis answered 2020-01-03T16:27:33Z
4 votes
我使用此代码,它能正常工作,希望对您有所帮助。
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;
}
Jay answered 2020-01-03T16:28:17Z
0 votes
// 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;
Nadeeshan Herath answered 2020-01-03T16:28:33Z
-9 votes
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 aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
//System.out.println("alias certificates :"+alias);
if (keystore.isKeyEntry(alias)) {
keystore.getKey(alias, password);
}
}
ramesh v answered 2020-01-03T16:28:48Z