从CertificationRequest到X509Certificate

时间:2012-05-23 11:10:27

标签: java x509certificate

实现org.jscep.server.ScepServlet我需要为方法doEnroll(List<X509Certificate> doEnroll(CertificationRequest certificationRequest))提供一个实现。

如何从提供的CertificationRequest获取返回X509Certificate?

除了CertificationRequest,我还有我需要用于签名的证书

只需从认证请求中获取公钥就足够了,因为我有其余的代码用于生成证书。

到目前为止我所拥有的:

protected List<X509Certificate> doEnroll(CertificationRequest certificationRequest) throws OperationFailureException, Exception {
    CaCertificate caCertificate = getSelfSignedCertificate();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(caCertificate.getCertificate().getSubjectX500Principal());
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(certificationRequest.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(publicKey); // this is basically what I need

    X509Certificate issuedCert = certGen.generate(caCertificate.getKeypair().getPrivate());

    List<X509Certificate> x509Certificates = new ArrayList<X509Certificate>();
    x509Certificates.add(issuedCert);

    return x509Certificates;
}

1 个答案:

答案 0 :(得分:0)

在jscep测试类中找到此方法:

public static PublicKey getPublicKey(CertificationRequest csr) throws IOException {
    SubjectPublicKeyInfo pubKeyInfo = csr.getCertificationRequestInfo().getSubjectPublicKeyInfo();
    RSAKeyParameters keyParams = (RSAKeyParameters) PublicKeyFactory.createKey(pubKeyInfo);
    KeySpec keySpec = new RSAPublicKeySpec(keyParams.getModulus(), keyParams.getExponent());

    try {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(keySpec);
    } catch (Exception e) {
        throw new IOException(e);
    }
}