java+创建+x509,如何使用Java创建X509证书?

I want to create a X509 certificate using Java language and then extract public key from it.

I have searched the internet and found many code examples, but all of them have errors (unknown variable or unknown type) or have many warnings that say something like : "the method ... from type ... is deprecated " etc.

For example, why the following code doesn't work:

PublicKey pk;

CertificateFactory cf = CertificateFactory.getInstance("X.509");

String PKstr = pk.toString();

InputStream PKstream = new ByteArrayInputStream(PKstr.getBytes());

X509Certificate pkcert = (X509Certificate)cf.generateCertificate(PKstream);

Can anyone show me how to create a certificate using pure Java or Bouncy Castle and then get a public key from that?

Thanks all.

解决方案

You can also generate a certificate using only JDK classes. The disadvantage is that you have to use two classes from the sun.security.x509 package.

The code would be:

KeyStore keyStore = ... // your keystore

// generate the certificate

// first parameter = Algorithm

// second parameter = signrature algorithm

// third parameter = the provider to use to generate the keys (may be null or

// use the constructor without provider)

CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA", null);

// generate it with 2048 bits

certGen.generate(2048);

// prepare the validity of the certificate

long validSecs = (long) 365 * 24 * 60 * 60; // valid for one year

// add the certificate information, currently only valid for one year.

X509Certificate cert = certGen.getSelfCertificate(

// enter your details according to your application

new X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"), validSecs);

// set the certificate and the key in the keystore

keyStore.setKeyEntry(certAlias, certGen.getPrivateKey(), null,

new X509Certificate[] { cert });

Retrieve the private key from the key store to encrypt or decrypt data.

Based on the code is from http://www.pixelstech.net/article/1408524957-Generate-cetrificate-in-Java----3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值