Search in sources :

Example 1 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project poi by apache.

the class PkiTestUtils method createOcspResp.

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
    // request
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);
    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);
    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }
    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
    }
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
    return ocspResp;
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 2 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project wso2-synapse by wso2.

the class OCSPVerifierTest method testOCSPVerifier.

/**
 * A fake certificate signed by a fake CA is made as the revoked certificate. The created OCSP response to the
 * OCSP request will say that that the fake peer certificate is revoked. the SingleResp derived from the OCSP
 * response will be put the the cache against the serial number of the fake peer certificate. Since the SingleResp
 * which corresponds to the revokedSerialNumber is in the cache, there will NOT be a call to a remote OCSP server.
 * Note that the serviceUrl passed to cache.setCacheValue(..) is null since it is not needed.
 *
 * @throws Exception
 */
public void testOCSPVerifier() throws Exception {
    // Add BouncyCastle as Security Provider.
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Utils utils = new Utils();
    // Create fake CA certificate.
    KeyPair caKeyPair = utils.generateRSAKeyPair();
    X509Certificate caCert = utils.generateFakeRootCert(caKeyPair);
    // Create fake peer certificate signed by the fake CA private key. This will be a revoked certificate.
    KeyPair peerKeyPair = utils.generateRSAKeyPair();
    BigInteger revokedSerialNumber = BigInteger.valueOf(111);
    X509Certificate revokedCertificate = generateFakePeerCert(revokedSerialNumber, peerKeyPair.getPublic(), caKeyPair.getPrivate(), caCert);
    // Create OCSP request to check if certificate with "serialNumber == revokedSerialNumber" is revoked.
    OCSPReq request = getOCSPRequest(caCert, revokedSerialNumber);
    // Create OCSP response saying that certificate with given serialNumber is revoked.
    // CertificateID revokedID = new CertificateID(CertificateID.HASH_SHA1, caCert, revokedSerialNumber);
    byte[] issuerCertEnc = caCert.getEncoded();
    X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();
    // CertID structure is used to uniquely identify certificates that are the subject of
    // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560
    CertificateID revokedID = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, revokedSerialNumber);
    OCSPResp response = generateOCSPResponse(request, certificateHolder, caKeyPair.getPrivate(), caKeyPair.getPublic(), revokedID);
    SingleResp singleResp = ((BasicOCSPResp) response.getResponseObject()).getResponses()[0];
    OCSPCache cache = OCSPCache.getCache();
    cache.init(5, 5);
    cache.setCacheValue(revokedSerialNumber, singleResp, request, null);
    OCSPVerifier ocspVerifier = new OCSPVerifier(cache);
    RevocationStatus status = ocspVerifier.checkRevocationStatus(revokedCertificate, caCert);
    // the cache will have the SingleResponse derived from the OCSP response and it will be checked to see if the
    // fake certificate is revoked. So the status should be REVOKED.
    assertTrue(status == RevocationStatus.REVOKED);
}
Also used : OCSPCache(org.apache.synapse.transport.certificatevalidation.ocsp.OCSPCache) X509Certificate(java.security.cert.X509Certificate) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPVerifier(org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier)

Example 3 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project pdfbox by apache.

the class CreateSignatureBase method sign.

/**
 * SignatureInterface implementation.
 *
 * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
 * The given InputStream contains the bytes that are given by the byte range.
 *
 * This method is for internal use only.
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 *
 * @throws IOException
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    // cannot be done private (interface)
    try {
        List<Certificate> certList = new ArrayList<>();
        certList.addAll(Arrays.asList(certificateChain));
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(certificateChain[0].getEncoded());
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
        gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        if (tsaUrl != null && tsaUrl.length() > 0) {
            ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
            signedData = validation.addSignedTimeStamp(signedData);
        }
        return signedData.getEncoded();
    } catch (GeneralSecurityException | CMSException | OperatorCreationException e) {
        throw new IOException(e);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) Store(org.bouncycastle.util.Store) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) KeyStore(java.security.KeyStore) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CMSException(org.bouncycastle.cms.CMSException)

Example 4 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project keystore-explorer by kaikramer.

the class JarSigner method createSignatureBlock.

private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException {
    try {
        List<X509Certificate> certList = new ArrayList<>();
        Collections.addAll(certList, certificateChain);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
        JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()).setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
        if (provider != null) {
            csb.setProvider(provider);
        }
        JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);
        // remove cmsAlgorithmProtect for compatibility reasons
        SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
        final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
        sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {

            @Override
            public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
                AttributeTable ret = sAttrGen.getAttributes(parameters);
                return ret.remove(CMSAttributes.cmsAlgorithmProtect);
            }
        }, sigGen.getUnsignedAttributeTableGenerator());
        CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
        dataGen.addSignerInfoGenerator(sigGen);
        dataGen.addCertificates(new JcaCertStore(certList));
        CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);
        // now let TSA time-stamp the signature
        if (tsaUrl != null && !tsaUrl.isEmpty()) {
            signedData = addTimestamp(tsaUrl, signedData);
        }
        return signedData.getEncoded();
    } catch (Exception ex) {
        throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) DefaultSignedAttributeTableGenerator(org.bouncycastle.cms.DefaultSignedAttributeTableGenerator) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CryptoException(org.kse.crypto.CryptoException) IOException(java.io.IOException) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CMSAttributeTableGenerator(org.bouncycastle.cms.CMSAttributeTableGenerator) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CryptoException(org.kse.crypto.CryptoException) Map(java.util.Map)

Example 5 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project structr by structr.

the class SignedJarBuilder method writeSignatureBlock.

/**
 * Write the certificate file with a digital signature.
 */
private void writeSignatureBlock(final JarOutputStream jos, final CMSTypedData data, final X509Certificate publicKey, final PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    final List<X509Certificate> certList = new ArrayList<>();
    certList.add(publicKey);
    final JcaCertStore certs = new JcaCertStore(certList);
    final CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    final ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm()).build(privateKey);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    final CMSSignedData sigData = gen.generate(data, false);
    final ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    final DEROutputStream dos = new DEROutputStream(jos);
    dos.writeObject(asn1.readObject());
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Aggregations

JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)23 X509Certificate (java.security.cert.X509Certificate)16 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)15 ContentSigner (org.bouncycastle.operator.ContentSigner)13 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)12 JcaCertStore (org.bouncycastle.cert.jcajce.JcaCertStore)12 CMSSignedData (org.bouncycastle.cms.CMSSignedData)12 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)12 ArrayList (java.util.ArrayList)11 JcaSignerInfoGeneratorBuilder (org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder)11 DigestCalculatorProvider (org.bouncycastle.operator.DigestCalculatorProvider)10 IOException (java.io.IOException)9 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)9 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)7 BigInteger (java.math.BigInteger)6 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)6 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)6 DigestCalculator (org.bouncycastle.operator.DigestCalculator)6 OCSPReq (org.bouncycastle.cert.ocsp.OCSPReq)5 SingleResp (org.bouncycastle.cert.ocsp.SingleResp)5