java - how to store a key in keystore

后端 未结 1 1400
臣服心动
臣服心动 2021-02-02 13:01

I\'ve need to store 2 keys into KeyStore Here\'s the relevant code:

KeyStore ks = KeyStore.getInstance(\"JKS\");
String password = \"password\";
char[] ksPass =          


        
1条回答
  •  礼貌的吻别
    2021-02-02 13:34

    You need to also provide the certificate (public key) for the private key entry. For a certificate signed by a CA, the chain is the CA's certificate and the end-certificate. For a self-signed certificate you only have the self-signed certificate
    Example:

    KeyPair keyPair = ...;//You already have this  
    X509Certificate certificate = generateCertificate(keyPair);  
    KeyStore keyStore = KeyStore.getInstance("JKS");  
    keyStore.load(null,null);  
    Certificate[] certChain = new Certificate[1];  
    certChain[0] = certificate;  
    keyStore.setKeyEntry("key1", (Key)keyPair.getPrivate(), pwd, certChain);  
    

    To generate the certificate follow this link:
    Example:

    public X509Certificate generateCertificate(KeyPair keyPair){  
       X509V3CertificateGenerator cert = new X509V3CertificateGenerator();   
       cert.setSerialNumber(BigInteger.valueOf(1));   //or generate a random number  
       cert.setSubjectDN(new X509Principal("CN=localhost"));  //see examples to add O,OU etc  
       cert.setIssuerDN(new X509Principal("CN=localhost")); //same since it is self-signed  
       cert.setPublicKey(keyPair.getPublic());  
       cert.setNotBefore();  
       cert.setNotAfter();  
       cert.setSignatureAlgorithm("SHA1WithRSAEncryption");   
        PrivateKey signingKey = keyPair.getPrivate();    
       return cert.generate(signingKey, "BC");  
    }
    

    0 讨论(0)
提交回复
热议问题