我如何以编程方式创build一个新的KeyStore?
我试图以编程方式在Java中创build一个新的密钥库。 以下代码:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.setCertificateEntry("alias", cert);
引发未初始化的KeyStoreexception。
KeyStore需要在创build后加载。 load方法要求FileInputStream从中读取,但是如果您提供一个空值,则将加载一个空的KeyStore。
看到这个链接
要在Java中创build一个新的KeyStore,首先需要创buildKeyStore文件,然后使用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();
我希望这有帮助,你可以在这里看到更多的信息。
// 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;
我使用这个代码,它的工作原理,希望它可以帮助。
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; }
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); } }