JAVA程序签发数字证书


1 )从密钥库中读取 CA 的证书
FileInputStream in=new FileInputStream(".keystore");
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in,storepass.toCharArray());
java.security.cert.Certificate c1=ks.getCertificate("caroot");
2 )从密钥库中读取 CA 的私钥
PrivateKey caprk=(PrivateKey)ks.getKey(alias,cakeypass.toCharArray());
3 )从 CA 的证书中提取签发者的信息
byte[] encod1=c1.getEncoded();
提取 CA 证书的编码
X509CertImpl cimp1=new X509CertImpl(encod1);
用该编码创建 X509CertImpl 类型对象
X509CertInfo cinfo1=(X509CertInfo)cimp1.get(X509CertImpl.NAME+"."+X509CertImpl.INFO);
获取 X509CertInfo 对象 X500Name issuer=(X500Name)cinfo1.get(X509CertInfo.SUBJECT+"."+CertificateIssuerName.DN_NAME); 获取 X509Name 类型的签发者信息
4 )获取待签发的证书
CertificateFactory cf=CertificateFactory.getInstance("X.509");
FileInputStream in2=new FileInputStream("user.csr");
java.security.cert.Certificate c2=cf.generateCertificate(in);
5 )从待签发的证书中提取证书信息
byte [] encod2=c2.getEncoded();
X509CertImpl cimp2=new X509CertImpl(encod2);
用该编码创建 X509CertImpl 类型对象
X509CertInfo cinfo2=(X509CertInfo)cimp2.get(X509CertImpl.NAME+"."+X509CertImpl.INFO);
获取 X509CertInfo 对象 6 )设置新证书有效期
Date begindate=new Date();
获取当前时间
Date enddate=new Date(begindate.getTime()+3000*24*60*60*1000L);
有效期为 3000
CertificateValidity cv=new CertificateValidity(begindate,enddate);
创建对象
cinfo2.set(X509CertInfo.VALIDITY,cv);
设置有效期

7)设置新证书序列号
int sn=(int)(begindate.getTime()/1000);
以当前时间为序列号
CertificateSerialNumber csn=new CertificateSerialNumber(sn);
cinfo2.set(X509CertInfo.SERIAL_NUMBER,csn);
8)设置新证书签发者
cinfo2.set(X509CertInfo.ISSUER+"."+CertificateIssuerName.DN_NAME,issuer);
应用第三步的结果
9)设置新证书签名算法信息
AlgorithmId algorithm=new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
cinfo2.set(CertificateAlgorithmId.NAME+"."+CertificateAlgorithmId.ALGORITHM,algorithm);
10)创建证书并使用CA的私钥对其签名
X509CertImpl newcert=new X509CertImpl(cinfo2);
newcert.sign(caprk,"MD5WithRSA");
使用CA私钥对其签名
11)将新证书写入密钥库
ks.setCertificateEntry("lf_signed",newcert);
FileOutputStream out=new FileOutputStream("newstore");
ks.store(out,"newpass".toCharArray());
这里是写入了新的密钥库,也可以使用第七条来增加条目

你可能感兴趣的:(安全认证)