Search in sources :

Example 36 with CMSException

use of org.bouncycastle.cms.CMSException in project pdfbox by apache.

the class CertInformationCollector method getCertInfo.

/**
 * Processes one signature and its including certificates.
 *
 * @param signatureContent the byte[]-Content of the signature
 * @return the CertSignatureInformation for this signature
 * @throws IOException
 * @throws CertificateProccessingException
 */
private CertSignatureInformation getCertInfo(byte[] signatureContent) throws CertificateProccessingException, IOException {
    rootCertInfo = new CertSignatureInformation();
    rootCertInfo.signatureHash = CertInformationHelper.getSha1Hash(signatureContent);
    try {
        CMSSignedData signedData = new CMSSignedData(signatureContent);
        Store<X509CertificateHolder> certificatesStore = signedData.getCertificates();
        SignerInformation signerInformation = processSignerStore(certificatesStore, signedData, rootCertInfo);
        addTimestampCerts(signerInformation);
    } catch (CMSException e) {
        LOG.error("Error occurred getting Certificate Information from Signature", e);
        throw new CertificateProccessingException(e);
    }
    return rootCertInfo;
}
Also used : X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) SignerInformation(org.bouncycastle.cms.SignerInformation) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSException(org.bouncycastle.cms.CMSException)

Example 37 with CMSException

use of org.bouncycastle.cms.CMSException in project pdfbox by apache.

the class CertInformationCollector method addTimestampCerts.

/**
 * Processes an embedded signed timestamp, that has been placed into a signature. The
 * certificates and its chain(s) will be processed the same way as the signature itself.
 *
 * @param signerInformation of the signature, to get unsigned attributes from it.
 * @throws IOException
 * @throws CertificateProccessingException
 */
private void addTimestampCerts(SignerInformation signerInformation) throws IOException, CertificateProccessingException {
    AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
    if (unsignedAttributes == null) {
        return;
    }
    Attribute tsAttribute = signerInformation.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
    if (tsAttribute.getAttrValues() instanceof DERSet) {
        DERSet tsSet = (DERSet) tsAttribute.getAttrValues();
        tsSet.getEncoded("DER");
        DERSequence tsSeq = (DERSequence) tsSet.getObjectAt(0);
        try {
            TimeStampToken tsToken = new TimeStampToken(new CMSSignedData(tsSeq.getEncoded("DER")));
            rootCertInfo.tsaCerts = new CertSignatureInformation();
            @SuppressWarnings("unchecked") Store<X509CertificateHolder> certificatesStore = tsToken.getCertificates();
            processSignerStore(certificatesStore, tsToken.toCMSSignedData(), rootCertInfo.tsaCerts);
        } catch (TSPException | CMSException e) {
            throw new IOException("Error parsing timestamp token", e);
        }
    }
}
Also used : Attribute(org.bouncycastle.asn1.cms.Attribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) IOException(java.io.IOException) DERSet(org.bouncycastle.asn1.DERSet) CMSSignedData(org.bouncycastle.cms.CMSSignedData) DERSequence(org.bouncycastle.asn1.DERSequence) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) CMSException(org.bouncycastle.cms.CMSException)

Example 38 with CMSException

use of org.bouncycastle.cms.CMSException in project jmeter by apache.

the class SMIMEAssertion method getResult.

public static AssertionResult getResult(SMIMEAssertionTestElement testElement, SampleResult response, String name) {
    checkForBouncycastle();
    AssertionResult res = new AssertionResult(name);
    try {
        MimeMessage msg;
        final int msgPos = testElement.getSpecificMessagePositionAsInt();
        if (msgPos < 0) {
            // means counting from end
            SampleResult[] subResults = response.getSubResults();
            final int pos = subResults.length + msgPos;
            log.debug("Getting message number: {} of {}", pos, subResults.length);
            msg = getMessageFromResponse(response, pos);
        } else {
            log.debug("Getting message number: {}", msgPos);
            msg = getMessageFromResponse(response, msgPos);
        }
        SMIMESignedParser signedParser = null;
        if (log.isDebugEnabled()) {
            log.debug("Content-type: {}", msg.getContentType());
        }
        if (msg.isMimeType("multipart/signed")) {
            // $NON-NLS-1$
            MimeMultipart multipart = (MimeMultipart) msg.getContent();
            signedParser = new SMIMESignedParser(new BcDigestCalculatorProvider(), multipart);
        } else if (// $NON-NLS-1$
        msg.isMimeType("application/pkcs7-mime") || msg.isMimeType("application/x-pkcs7-mime")) {
            // $NON-NLS-1$
            signedParser = new SMIMESignedParser(new BcDigestCalculatorProvider(), msg);
        }
        if (null != signedParser) {
            log.debug("Found signature");
            if (testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is signed");
            } else if (testElement.isVerifySignature() || !testElement.isSignerNoCheck()) {
                res = verifySignature(testElement, signedParser, name);
            }
        } else {
            log.debug("Did not find signature");
            if (!testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is not signed");
            }
        }
    } catch (MessagingException e) {
        String msg = "Cannot parse mime msg: " + e.getMessage();
        log.warn(msg, e);
        res.setFailure(true);
        res.setFailureMessage(msg);
    } catch (CMSException e) {
        res.setFailure(true);
        res.setFailureMessage("Error reading the signature: " + e.getMessage());
    } catch (SMIMEException e) {
        res.setFailure(true);
        res.setFailureMessage("Cannot extract signed body part from signature: " + e.getMessage());
    } catch (IOException e) {
        // should never happen
        log.error("Cannot read mime message content: {}", e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    }
    return res;
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SMIMESignedParser(org.bouncycastle.mail.smime.SMIMESignedParser) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) SampleResult(org.apache.jmeter.samplers.SampleResult) CMSException(org.bouncycastle.cms.CMSException)

Example 39 with CMSException

use of org.bouncycastle.cms.CMSException in project zm-mailbox by Zimbra.

the class MobileConfigFormatter method signConfig.

private byte[] signConfig(Domain domain, Server server, byte[] config) {
    byte[] signedConfig = config;
    String certStr = null;
    String pvtKeyStr = null;
    if (domain != null) {
        certStr = domain.getSSLCertificate();
        pvtKeyStr = domain.getSSLPrivateKey();
        if (StringUtil.isNullOrEmpty(certStr) && server != null) {
            certStr = server.getSSLCertificate();
            pvtKeyStr = server.getSSLPrivateKey();
        }
    }
    if (!StringUtil.isNullOrEmpty(certStr) && !StringUtil.isNullOrEmpty(pvtKeyStr)) {
        try (InputStream targetStream = new ByteArrayInputStream(certStr.getBytes())) {
            CertificateFactory certFactory = CertificateFactory.getInstance(SmimeConstants.PUB_CERT_TYPE);
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(targetStream);
            StringReader reader = new StringReader(pvtKeyStr);
            PrivateKey privateKey = null;
            try (PEMParser pp = new PEMParser(reader)) {
                Object pemKP = pp.readObject();
                JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
                PrivateKeyInfo pkInfo = null;
                if (pemKP instanceof PrivateKeyInfo) {
                    pkInfo = (PrivateKeyInfo) pemKP;
                } else {
                    pkInfo = ((PEMKeyPair) pemKP).getPrivateKeyInfo();
                }
                privateKey = converter.getPrivateKey(pkInfo);
            }
            signedConfig = DataSigner.signData(config, cert, privateKey);
        } catch (IOException | CertificateException | OperatorCreationException | CMSException e) {
            ZimbraLog.misc.debug("exception occurred during signing config", e);
        }
    } else {
        ZimbraLog.misc.debug("SSLCertificate/SSLPrivateKey is not set, config will not be signed");
    }
    return signedConfig;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) PEMParser(org.bouncycastle.openssl.PEMParser) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) CMSException(org.bouncycastle.cms.CMSException)

Example 40 with CMSException

use of org.bouncycastle.cms.CMSException in project athenz by yahoo.

the class Crypto method validatePKCS7Signature.

// /CLOVER:OFF
public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) {
    try {
        SignerInformationStore signerStore;
        try (InputStream sigIs = new ByteArrayInputStream(Base64.decode(signature.getBytes(StandardCharsets.UTF_8)))) {
            CMSProcessable content = new CMSProcessableByteArray(data.getBytes(StandardCharsets.UTF_8));
            CMSSignedData signedData = new CMSSignedData(content, sigIs);
            signerStore = signedData.getSignerInfos();
        }
        Collection<SignerInformation> signers = signerStore.getSigners();
        Iterator<SignerInformation> it = signers.iterator();
        SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC_PROVIDER).build(publicKey);
        while (it.hasNext()) {
            SignerInformation signerInfo = it.next();
            if (signerInfo.verify(infoVerifier)) {
                return true;
            }
        }
    } catch (CMSException ex) {
        LOG.error("validatePKCS7Signature: unable to initialize CMSSignedData object: {}", ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error("validatePKCS7Signature: Caught OperatorCreationException when creating JcaSimpleSignerInfoVerifierBuilder: {}", ex.getMessage());
        throw new CryptoException(ex);
    } catch (IOException ex) {
        LOG.error("validatePKCS7Signature: Caught IOException when closing InputStream: {}", ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("validatePKCS7Signature: unable to validate signature: {}", ex.getMessage());
        throw new CryptoException(ex.getMessage());
    }
    return false;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSProcessable(org.bouncycastle.cms.CMSProcessable) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMException(org.bouncycastle.openssl.PEMException) UnknownHostException(java.net.UnknownHostException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

CMSException (org.bouncycastle.cms.CMSException)41 CMSSignedData (org.bouncycastle.cms.CMSSignedData)30 IOException (java.io.IOException)28 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 X509Certificate (java.security.cert.X509Certificate)18 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)14 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)14 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)13 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 CertificateException (java.security.cert.CertificateException)10 SignerInformation (org.bouncycastle.cms.SignerInformation)9 CMSAbsentContent (org.bouncycastle.cms.CMSAbsentContent)8 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)8 InputStream (java.io.InputStream)7 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)7 TSPException (org.bouncycastle.tsp.TSPException)7 CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)7 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)6 Attribute (org.bouncycastle.asn1.cms.Attribute)6 CMSTypedData (org.bouncycastle.cms.CMSTypedData)6