Search in sources :

Example 1 with DigestCalculator

use of org.bouncycastle.operator.DigestCalculator 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 DigestCalculator

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

the class SignerInformation method doVerify.

private boolean doVerify(SignerInformationVerifier verifier) throws CMSException {
    String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
    ContentVerifier contentVerifier;
    try {
        contentVerifier = verifier.getContentVerifier(encryptionAlgorithm, info.getDigestAlgorithm());
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create content verifier: " + e.getMessage(), e);
    }
    try {
        OutputStream sigOut = contentVerifier.getOutputStream();
        if (resultDigest == null) {
            DigestCalculator calc = verifier.getDigestCalculator(this.getDigestAlgorithmID());
            if (content != null) {
                OutputStream digOut = calc.getOutputStream();
                if (signedAttributeSet == null) {
                    if (contentVerifier instanceof RawContentVerifier) {
                        content.write(digOut);
                    } else {
                        OutputStream cOut = new TeeOutputStream(digOut, sigOut);
                        content.write(cOut);
                        cOut.close();
                    }
                } else {
                    content.write(digOut);
                    sigOut.write(this.getEncodedSignedAttributes());
                }
                digOut.close();
            } else if (signedAttributeSet != null) {
                sigOut.write(this.getEncodedSignedAttributes());
            } else {
                // TODO Get rid of this exception and just treat content==null as empty not missing?
                throw new CMSException("data not encapsulated in signature - use detached constructor.");
            }
            resultDigest = calc.getDigest();
        } else {
            if (signedAttributeSet == null) {
                if (content != null) {
                    content.write(sigOut);
                }
            } else {
                sigOut.write(this.getEncodedSignedAttributes());
            }
        }
        sigOut.close();
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create digest calculator: " + e.getMessage(), e);
    }
    // RFC 3852 11.1 Check the content-type attribute is correct
    {
        ASN1Primitive validContentType = getSingleValuedSignedAttribute(CMSAttributes.contentType, "content-type");
        if (validContentType == null) {
            if (!isCounterSignature && signedAttributeSet != null) {
                throw new CMSException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
            }
        } else {
            if (isCounterSignature) {
                throw new CMSException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
            }
            if (!(validContentType instanceof ASN1ObjectIdentifier)) {
                throw new CMSException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
            }
            ASN1ObjectIdentifier signedContentType = (ASN1ObjectIdentifier) validContentType;
            if (!signedContentType.equals(contentType)) {
                throw new CMSException("content-type attribute value does not match eContentType");
            }
        }
    }
    // RFC 3852 11.2 Check the message-digest attribute is correct
    {
        ASN1Primitive validMessageDigest = getSingleValuedSignedAttribute(CMSAttributes.messageDigest, "message-digest");
        if (validMessageDigest == null) {
            if (signedAttributeSet != null) {
                throw new CMSException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
            }
        } else {
            if (!(validMessageDigest instanceof ASN1OctetString)) {
                throw new CMSException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
            }
            ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
            if (!Arrays.constantTimeAreEqual(resultDigest, signedMessageDigest.getOctets())) {
                throw new CMSSignerDigestMismatchException("message-digest attribute value does not match calculated value");
            }
        }
    }
    // RFC 3852 11.4 Validate countersignature attribute(s)
    {
        AttributeTable signedAttrTable = this.getSignedAttributes();
        if (signedAttrTable != null && signedAttrTable.getAll(CMSAttributes.counterSignature).size() > 0) {
            throw new CMSException("A countersignature attribute MUST NOT be a signed attribute");
        }
        AttributeTable unsignedAttrTable = this.getUnsignedAttributes();
        if (unsignedAttrTable != null) {
            ASN1EncodableVector csAttrs = unsignedAttrTable.getAll(CMSAttributes.counterSignature);
            for (int i = 0; i < csAttrs.size(); ++i) {
                Attribute csAttr = (Attribute) csAttrs.get(i);
                if (csAttr.getAttrValues().size() < 1) {
                    throw new CMSException("A countersignature attribute MUST contain at least one AttributeValue");
                }
            // Note: We don't recursively validate the countersignature value
            }
        }
    }
    try {
        if (signedAttributeSet == null && resultDigest != null) {
            if (contentVerifier instanceof RawContentVerifier) {
                RawContentVerifier rawVerifier = (RawContentVerifier) contentVerifier;
                if (encName.equals("RSA")) {
                    DigestInfo digInfo = new DigestInfo(new AlgorithmIdentifier(digestAlgorithm.getAlgorithm(), DERNull.INSTANCE), resultDigest);
                    return rawVerifier.verify(digInfo.getEncoded(ASN1Encoding.DER), this.getSignature());
                }
                return rawVerifier.verify(resultDigest, this.getSignature());
            }
        }
        return contentVerifier.verify(this.getSignature());
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) Attribute(org.bouncycastle.asn1.cms.Attribute) ContentVerifier(org.bouncycastle.operator.ContentVerifier) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) OutputStream(java.io.OutputStream) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) DigestCalculator(org.bouncycastle.operator.DigestCalculator) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 3 with DigestCalculator

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

the class BcDigestCalculatorProvider method get.

public DigestCalculator get(final AlgorithmIdentifier algorithm) throws OperatorCreationException {
    Digest dig = digestProvider.get(algorithm);
    final DigestOutputStream stream = new DigestOutputStream(dig);
    return new DigestCalculator() {

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            return algorithm;
        }

        public OutputStream getOutputStream() {
            return stream;
        }

        public byte[] getDigest() {
            return stream.getDigest();
        }
    };
}
Also used : Digest(org.bouncycastle.crypto.Digest) ExtendedDigest(org.bouncycastle.crypto.ExtendedDigest) DigestCalculator(org.bouncycastle.operator.DigestCalculator)

Example 4 with DigestCalculator

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

the class AttributeCertificateHolder method match.

public boolean match(Object obj) {
    if (!(obj instanceof X509CertificateHolder)) {
        return false;
    }
    X509CertificateHolder x509Cert = (X509CertificateHolder) obj;
    if (holder.getBaseCertificateID() != null) {
        return holder.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) && matchesDN(x509Cert.getIssuer(), holder.getBaseCertificateID().getIssuer());
    }
    if (holder.getEntityName() != null) {
        if (matchesDN(x509Cert.getSubject(), holder.getEntityName())) {
            return true;
        }
    }
    if (holder.getObjectDigestInfo() != null) {
        try {
            DigestCalculator digCalc = digestCalculatorProvider.get(holder.getObjectDigestInfo().getDigestAlgorithm());
            OutputStream digOut = digCalc.getOutputStream();
            switch(getDigestedObjectType()) {
                case ObjectDigestInfo.publicKey:
                    // TODO: DSA Dss-parms
                    digOut.write(x509Cert.getSubjectPublicKeyInfo().getEncoded());
                    break;
                case ObjectDigestInfo.publicKeyCert:
                    digOut.write(x509Cert.getEncoded());
                    break;
            }
            digOut.close();
            if (!Arrays.areEqual(digCalc.getDigest(), getObjectDigest())) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
    return false;
}
Also used : OutputStream(java.io.OutputStream) DigestCalculator(org.bouncycastle.operator.DigestCalculator)

Example 5 with DigestCalculator

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

the class JcaDigestCalculatorProviderBuilder method build.

public DigestCalculatorProvider build() throws OperatorCreationException {
    return new DigestCalculatorProvider() {

        public DigestCalculator get(final AlgorithmIdentifier algorithm) throws OperatorCreationException {
            final DigestOutputStream stream;
            try {
                MessageDigest dig = helper.createDigest(algorithm);
                stream = new DigestOutputStream(dig);
            } catch (GeneralSecurityException e) {
                throw new OperatorCreationException("exception on setup: " + e, e);
            }
            return new DigestCalculator() {

                public AlgorithmIdentifier getAlgorithmIdentifier() {
                    return algorithm;
                }

                public OutputStream getOutputStream() {
                    return stream;
                }

                public byte[] getDigest() {
                    return stream.getDigest();
                }
            };
        }
    };
}
Also used : DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) GeneralSecurityException(java.security.GeneralSecurityException) DigestCalculator(org.bouncycastle.operator.DigestCalculator) MessageDigest(java.security.MessageDigest) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

DigestCalculator (org.bouncycastle.operator.DigestCalculator)14 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)7 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)7 IOException (java.io.IOException)6 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)6 JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)6 Date (java.util.Date)5 BigInteger (java.math.BigInteger)4 X509Certificate (java.security.cert.X509Certificate)4 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)4 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)4 SecureRandom (java.security.SecureRandom)3 CertificateEncodingException (java.security.cert.CertificateEncodingException)3 DERIA5String (org.bouncycastle.asn1.DERIA5String)3 DEROctetString (org.bouncycastle.asn1.DEROctetString)3 Extension (org.bouncycastle.asn1.x509.Extension)3 Extensions (org.bouncycastle.asn1.x509.Extensions)3 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)3 OCSPException (org.bouncycastle.cert.ocsp.OCSPException)3 OCSPReqBuilder (org.bouncycastle.cert.ocsp.OCSPReqBuilder)3