java 密钥保存在哪里,java - 如何在密钥库中存储密钥

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?

解决方案

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值