2011-03-15 75 views
44

我試圖以編程方式在Java中創建一個新的密鑰庫。以下代碼:如何以編程方式創建新的KeyStore?

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
keyStore.setCertificateEntry("alias", cert); 

引發未初始化的KeyStore異常。

回答

43

KeyStore需要在創建後加載。 load方法要求FileInputStream讀取,但如果您提供一個空值,則會加載一個空的KeyStore。

this link

+4

^鏈接:http://download.oracle.com/javase/6/docs/api/java/security/KeyStore.html#load%28java.io.InputStream,%20char[]%29 – 2011-03-15 13:56:28

58

要在Java中創建一個新的密鑰庫,你首先需要創建密鑰庫文件,然後保存它使用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(); 

我希望這可以幫助,你可以看到更多info here

-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); 
     } 
    } 
+2

您的代碼讀入java默認密鑰庫。問題是關於創建一個新的密鑰庫。 – 2013-07-02 17:02:47

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; 
+0

請考慮在您的答案中添加一些解釋,說明爲什麼它適用於OP – techspider 2016-06-13 18:27:15

2

我用這個代碼,它的工作原理,希望它能幫助。

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; 
} 
+0

而不是創建新的商店,我需要根據我所做的呼叫設置不同的商店,這會更改默認值。 – dezzer10 2017-10-24 18:34:52

相關問題