java - how to store a key in keystore

MichBoy picture MichBoy · Dec 15, 2012 · Viewed 40.2k times · Source

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

KeyStore ks = KeyStore.getInstance("JKS");
String password = "password";
char[] ksPass = password.toCharArray();
ks.load(null, ksPass);
ks.setKeyEntry("keyForSeckeyDecrypt", privateKey, null, null);
ks.setKeyEntry("keyForDigitalSignature", priv, null, null);
FileOutputStream writeStream = new FileOutputStream("key.store");
ks.store(writeStream, ksPass);
writeStream.close();

Though I get an execption "Private key must be accompanied by certificate chain"

What is that, exactly? and how would I generate it?

Answer

Cratylus picture Cratylus · Dec 15, 2012

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(<date>);  
   cert.setNotAfter(<date>);  
   cert.setSignatureAlgorithm("SHA1WithRSAEncryption");   
    PrivateKey signingKey = keyPair.getPrivate();    
   return cert.generate(signingKey, "BC");  
}