java – 如何在keystore中存储密钥

前端之家收集整理的这篇文章主要介绍了java – 如何在keystore中存储密钥前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要将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);
FileOutputStream writeStream = new FileOutputStream("key.store");
ks.store(writeStream,ksPass);
writeStream.close();

虽然我得到一个执行“私钥必须附有证书链”

那是什么呢?我将如何生成它?

解决方法

您还需要为私钥输入提供证书(公开密钥).对于由CA签发的证书,该链是CA的证书和结束证书.对于自签名证书,您只能拥有自签名证书
例:
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);

生成证书,请遵循link
例:

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");  
}

猜你在找的Java相关文章