/**
* 根据如下参数获取对应base64编码格式的证书文件字符串
* issuerName 与 reqName 对象是同一个则认为生成的是CA证书
* @param issuerName 颁发者信息
* @param reqName 请求证主题信息
* <br> issuerName == reqName ---> CA
* @param serial 证书序列号
* <br>eg: BigInteger serial = BigInteger.valueOf(System.currentTimeMillis() / 1000);
* @param notBefore 有效期开始时间 2018-08-01 00:00:00
* @param notAfter 有效期截至时间 2028-08-01 00:00:00
* @param userPublicKey 请求者主题公钥信息
* @param rootPrivateKey 颁发者私钥信息
* @return String
* @throws OperatorCreationException
* @throws CertificateException
* @throws IOException
*/
public static String certBuilder(X500Name issuerName, X500Name reqName, BigInteger serial, Date notBefore, Date notAfter, PublicKey userPublicKey, PrivateKey rootPrivateKey) throws OperatorCreationException, CertificateException, IOException {
JcaX509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder(
issuerName, serial, notBefore, notAfter, reqName, userPublicKey);
// 签发者 与 使用者 信息一致则是CA证书生成,增加CA 基本约束属性
if(issuerName == reqName){
BasicConstraints constraint = new BasicConstraints(1);
x509v3CertificateBuilder.addExtension(Extension.basicConstraints, false, constraint);
}
//签名的工具
ContentSigner signer = new JcaContentSignerBuilder("SHA256WITHRSA").setProvider("BC").build(rootPrivateKey);
//触发签名产生用户证书
X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(signer);
JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter();
certificateConverter.setProvider("BC");
Certificate userCertificate = certificateConverter.getCertificate(x509CertificateHolder);
String certStr = genCert(userCertificate);
return certStr;
}
/**
* 签发CA证书
*/
public void genCaCertTest() throws Exception{
//根证书Issue基本信息
X500Name issuerName = getX500Name("Dev", "VK", "BeiJing", "BeiJing", "CN", "R&D");
// 证书序列号
BigInteger serial = BigInteger.valueOf(System.currentTimeMillis() / 1000);
//证书有 起始日期 与 结束日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date notBefore = sdf.parse("2018-08-01 00:00:00");
Date notAfter = sdf.parse("2028-08-01 00:00:00");
//构建 用户证书 对应的公钥
PublicKey userPublicKey = getPublicKey(16,publicRootMudulus,publicRootexpoent);
//构建CAroot证书 对应的私钥
PrivateKey rootPrivateKey = getPrivateKey(16,publicRootMudulus,publicRootexpoent);
//构建证书的build
String cert = certBuilder(issuerName, issuerName, serial, notBefore, notAfter, userPublicKey, rootPrivateKey);
System.out.println("\n"+cert);
}