[英]java - how to store a key in keystore
I've need to store 2 keys into KeyStore Here's the relevant code: 我需要将2个密钥存储到KeyStore这里是相关的代码:
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" 虽然我得到了一个execption“私钥必须伴随证书链”
What is that, exactly? 那究竟是什么? and how would I generate it?
我将如何生成它?
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.
对于由CA签名的证书,该链是CA的证书和最终证书。 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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.