Search in sources :

Example 11 with DigestCalculator

use of org.bouncycastle.operator.DigestCalculator in project poi by apache.

the class PkiTestUtils method generateCertificate.

static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore, Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage) throws IOException, OperatorCreationException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X500Name issuerName;
    if (issuerCertificate != null) {
        issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer();
    } else {
        issuerName = new X500Name(subjectDn);
    }
    RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey;
    RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent());
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec);
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName, new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn), subjectPublicKeyInfo);
    X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc);
    SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
    AuthorityKeyIdentifier autKeyId = (issuerCertificate != null) ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded())) : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo);
    certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId);
    certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId);
    if (caFlag) {
        BasicConstraints bc;
        if (-1 == pathLength) {
            bc = new BasicConstraints(true);
        } else {
            bc = new BasicConstraints(pathLength);
        }
        certificateGenerator.addExtension(Extension.basicConstraints, false, bc);
    }
    if (null != crlUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        DERIA5String crlUriDer = new DERIA5String(crlUri);
        GeneralName gn = new GeneralName(uri, crlUriDer);
        DERSequence gnDer = new DERSequence(gn);
        GeneralNames gns = GeneralNames.getInstance(gnDer);
        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        DERSequence distpDer = new DERSequence(distp);
        certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer);
    }
    if (null != ocspUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        GeneralName ocspName = new GeneralName(uri, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }
    if (null != keyUsage) {
        certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage);
    }
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
    signerBuilder.setProvider("BC");
    X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey));
    //                        .getEncoded()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERSequence(org.bouncycastle.asn1.DERSequence) RSAPublicKey(java.security.interfaces.RSAPublicKey) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) SecureRandom(java.security.SecureRandom) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 12 with DigestCalculator

use of org.bouncycastle.operator.DigestCalculator in project ddf by codice.

the class OcspChecker method generateOcspRequest.

/**
 * Creates an {@link OCSPReq} to send to the OCSP server for the given certificate.
 *
 * @param cert - the certificate to verify
 * @return the created OCSP request
 * @throws OcspCheckerException after posting an alert to the admin console, if any error occurs
 */
@VisibleForTesting
OCSPReq generateOcspRequest(Certificate cert) throws OcspCheckerException {
    try {
        X509CertificateHolder issuerCert = resolveIssuerCertificate(cert);
        JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
        DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
        DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
        CertificateID certId = new CertificateID(digestCalculator, issuerCert, cert.getSerialNumber().getValue());
        OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
        ocspReqGenerator.addRequest(certId);
        return ocspReqGenerator.build();
    } catch (OCSPException | OperatorCreationException e) {
        throw new OcspCheckerException("Unable to create an OCSP request." + NOT_VERIFIED_MSG, e);
    }
}
Also used : DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 13 with DigestCalculator

use of org.bouncycastle.operator.DigestCalculator in project netty by netty.

the class OcspRequestBuilder method build.

/**
 * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce
 * and CA's will (should) reject subsequent requests that have the same nonce value.
 */
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
    SecureRandom generator = checkNotNull(this.generator, "generator");
    DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
    X509Certificate certificate = checkNotNull(this.certificate, "certificate");
    X509Certificate issuer = checkNotNull(this.issuer, "issuer");
    BigInteger serial = certificate.getSerialNumber();
    CertificateID certId = new CertificateID(calculator, new X509CertificateHolder(issuer.getEncoded()), serial);
    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.addRequest(certId);
    byte[] nonce = new byte[8];
    generator.nextBytes(nonce);
    Extension[] extensions = new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)) };
    builder.setRequestExtensions(new Extensions(extensions));
    return builder.build();
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SecureRandom(java.security.SecureRandom) BigInteger(java.math.BigInteger) Extensions(org.bouncycastle.asn1.x509.Extensions) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) X509Certificate(java.security.cert.X509Certificate) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 14 with DigestCalculator

use of org.bouncycastle.operator.DigestCalculator in project jruby-openssl by jruby.

the class OCSPBasicResponse method sign.

@JRubyMethod(name = "sign", rest = true)
public IRubyObject sign(final ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.getRuntime();
    int flag = 0;
    IRubyObject additionalCerts = context.nil;
    IRubyObject flags = context.nil;
    IRubyObject digest = context.nil;
    Digest digestInstance = new Digest(runtime, _Digest(runtime));
    List<X509CertificateHolder> addlCerts = new ArrayList<X509CertificateHolder>();
    switch(Arity.checkArgumentCount(runtime, args, 2, 5)) {
        case 3:
            additionalCerts = args[2];
            break;
        case 4:
            additionalCerts = args[2];
            flags = args[3];
            break;
        case 5:
            additionalCerts = args[2];
            flags = args[3];
            digest = args[4];
            break;
        default:
            break;
    }
    if (digest.isNil())
        digest = digestInstance.initialize(context, new IRubyObject[] { RubyString.newString(runtime, "SHA1") });
    if (!flags.isNil())
        flag = RubyFixnum.fix2int(flags);
    if (additionalCerts.isNil())
        flag |= RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCERTS));
    X509Cert signer = (X509Cert) args[0];
    PKey signerKey = (PKey) args[1];
    String keyAlg = signerKey.getAlgorithm();
    String digAlg = ((Digest) digest).getShortAlgorithm();
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(digAlg + "with" + keyAlg);
    signerBuilder.setProvider("BC");
    ContentSigner contentSigner = null;
    try {
        contentSigner = signerBuilder.build(signerKey.getPrivateKey());
    } catch (OperatorCreationException e) {
        throw newOCSPError(runtime, e);
    }
    BasicOCSPRespBuilder respBuilder = null;
    try {
        if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_RESPID_KEY))) != 0) {
            JcaDigestCalculatorProviderBuilder dcpb = new JcaDigestCalculatorProviderBuilder();
            dcpb.setProvider("BC");
            DigestCalculatorProvider dcp = dcpb.build();
            DigestCalculator calculator = dcp.get(contentSigner.getAlgorithmIdentifier());
            respBuilder = new BasicOCSPRespBuilder(SubjectPublicKeyInfo.getInstance(signerKey.getPublicKey().getEncoded()), calculator);
        } else {
            respBuilder = new BasicOCSPRespBuilder(new RespID(signer.getSubject().getX500Name()));
        }
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    X509CertificateHolder[] chain = null;
    try {
        if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCERTS))) == 0) {
            addlCerts.add(new X509CertificateHolder(signer.getAuxCert().getEncoded()));
            if (!additionalCerts.isNil()) {
                Iterator<java.security.cert.Certificate> rubyAddlCerts = ((RubyArray) additionalCerts).iterator();
                while (rubyAddlCerts.hasNext()) {
                    java.security.cert.Certificate cert = rubyAddlCerts.next();
                    addlCerts.add(new X509CertificateHolder(cert.getEncoded()));
                }
            }
            chain = addlCerts.toArray(new X509CertificateHolder[addlCerts.size()]);
        }
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    Date producedAt = null;
    if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOTIME))) == 0) {
        producedAt = new Date();
    }
    for (OCSPSingleResponse resp : singleResponses) {
        SingleResp singleResp = new SingleResp(resp.getBCSingleResp());
        respBuilder.addResponse(singleResp.getCertID(), singleResp.getCertStatus(), singleResp.getThisUpdate(), singleResp.getNextUpdate(), resp.getBCSingleResp().getSingleExtensions());
    }
    try {
        Extension[] respExtAry = new Extension[extensions.size()];
        Extensions respExtensions = new Extensions(extensions.toArray(respExtAry));
        BasicOCSPResp bcBasicOCSPResp = respBuilder.setResponseExtensions(respExtensions).build(contentSigner, chain, producedAt);
        asn1BCBasicOCSPResp = BasicOCSPResponse.getInstance(bcBasicOCSPResp.getEncoded());
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    return this;
}
Also used : RubyArray(org.jruby.RubyArray) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) DigestCalculator(org.bouncycastle.operator.DigestCalculator) RubyString(org.jruby.RubyString) IRubyObject(org.jruby.runtime.builtin.IRubyObject) Extensions(org.bouncycastle.asn1.x509.Extensions) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Ruby(org.jruby.Ruby) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) Digest._Digest(org.jruby.ext.openssl.Digest._Digest) MessageDigest(java.security.MessageDigest) ContentSigner(org.bouncycastle.operator.ContentSigner) RubyFixnum(org.jruby.RubyFixnum) RaiseException(org.jruby.exceptions.RaiseException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) Date(java.util.Date) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) RespID(org.bouncycastle.cert.ocsp.RespID) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) X509AuxCertificate(org.jruby.ext.openssl.x509store.X509AuxCertificate) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 15 with DigestCalculator

use of org.bouncycastle.operator.DigestCalculator in project jruby-openssl by jruby.

the class OCSPCertificateId method initializeImpl.

private IRubyObject initializeImpl(final ThreadContext context, BigInteger serial, IRubyObject issuerCert, IRubyObject digest) {
    Ruby runtime = context.getRuntime();
    Digest rubyDigest = (Digest) digest;
    ASN1ObjectIdentifier oid = ASN1.sym2Oid(runtime, rubyDigest.getName().toLowerCase());
    AlgorithmIdentifier bcAlgId = new AlgorithmIdentifier(oid);
    BcDigestCalculatorProvider calculatorProvider = new BcDigestCalculatorProvider();
    DigestCalculator calc;
    try {
        calc = calculatorProvider.get(bcAlgId);
    } catch (OperatorCreationException e) {
        throw newOCSPError(runtime, e);
    }
    X509Cert rubyCert = (X509Cert) issuerCert;
    try {
        this.bcCertId = new CertificateID(calc, new X509CertificateHolder(rubyCert.getAuxCert().getEncoded()), serial).toASN1Primitive();
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    return this;
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) Digest._Digest(org.jruby.ext.openssl.Digest._Digest) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Ruby(org.jruby.Ruby) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) RaiseException(org.jruby.exceptions.RaiseException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

DigestCalculator (org.bouncycastle.operator.DigestCalculator)17 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)8 IOException (java.io.IOException)7 BigInteger (java.math.BigInteger)7 Date (java.util.Date)7 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)7 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)7 JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)7 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)6 SecureRandom (java.security.SecureRandom)5 Extension (org.bouncycastle.asn1.x509.Extension)5 Extensions (org.bouncycastle.asn1.x509.Extensions)5 X509Certificate (java.security.cert.X509Certificate)4 DEROctetString (org.bouncycastle.asn1.DEROctetString)4 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)4 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)4 OCSPReq (org.bouncycastle.cert.ocsp.OCSPReq)4 OCSPResp (org.bouncycastle.cert.ocsp.OCSPResp)4 ContentSigner (org.bouncycastle.operator.ContentSigner)4 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)4