Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - how to store a key in keystore

Tags:

java

keystore

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?

like image 532
MichBoy Avatar asked Dec 15 '12 17:12

MichBoy


People also ask

Where does jks store keys?

By default, Java has a keystore file located at JAVA_HOME/jre/lib/security/cacerts.

How do I save a private key in Java?

Store/Retrieve Private Key/Public Key to/from disk/file :D. PrivateKey privateKey = keyPair. getPrivate(); PublicKey publicKey = keyPair.


1 Answers

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");  
}
like image 105
Cratylus Avatar answered Oct 02 '22 12:10

Cratylus