Search in sources :

Example 6 with CMSProcessable

use of org.bouncycastle.cms.CMSProcessable in project sic by belluccifranco.

the class AfipWebServiceSOAPClient method crearCMS.

public byte[] crearCMS(byte[] p12file, String p12pass, String signer, String service, long ticketTime) {
    PrivateKey pKey = null;
    X509Certificate pCertificate = null;
    byte[] asn1_cms = null;
    CertStore cstore = null;
    try {
        KeyStore ks = KeyStore.getInstance("pkcs12");
        InputStream is;
        is = Utilidades.convertirByteArrayToInputStream(p12file);
        ks.load(is, p12pass.toCharArray());
        is.close();
        pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
        pCertificate = (X509Certificate) ks.getCertificate(signer);
        ArrayList<X509Certificate> certList = new ArrayList<>();
        certList.add(pCertificate);
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_certificado_error"));
    }
    String loginTicketRequest_xml = this.crearTicketRequerimientoAcceso(service, ticketTime);
    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);
        generator.addCertificatesAndCRLs(cstore);
        CMSProcessable data = new CMSProcessableByteArray(loginTicketRequest_xml.getBytes());
        CMSSignedData signed = generator.generate(data, true, "BC");
        asn1_cms = signed.getEncoded();
    } catch (IllegalArgumentException | CertStoreException | CMSException | NoSuchAlgorithmException | NoSuchProviderException | IOException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_firmando_certificado_error"));
    }
    return asn1_cms;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) BusinessServiceException(sic.service.BusinessServiceException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InputStream(java.io.InputStream) CertStoreException(java.security.cert.CertStoreException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSProcessable(org.bouncycastle.cms.CMSProcessable) NoSuchProviderException(java.security.NoSuchProviderException) CertStore(java.security.cert.CertStore) CMSException(org.bouncycastle.cms.CMSException)

Example 7 with CMSProcessable

use of org.bouncycastle.cms.CMSProcessable 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)

Example 8 with CMSProcessable

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

the class ShowSignature method verifyPKCS7.

/**
 * Verify a PKCS7 signature.
 *
 * @param signedContentAsStream the byte sequence that has been signed
 * @param contents the /Contents field as a COSString
 * @param sig the PDF signature (the /V dictionary)
 * @throws CMSException
 * @throws OperatorCreationException
 * @throws GeneralSecurityException
 * @throws CertificateVerificationException
 */
private void verifyPKCS7(InputStream signedContentAsStream, byte[] contents, PDSignature sig) throws CMSException, OperatorCreationException, CertificateVerificationException, GeneralSecurityException, TSPException, IOException {
    // inspiration:
    // http://stackoverflow.com/a/26702631/535646
    // http://stackoverflow.com/a/9261365/535646
    CMSProcessable signedContent = new CMSProcessableInputStream(signedContentAsStream);
    CMSSignedData signedData = new CMSSignedData(signedContent, contents);
    Store<X509CertificateHolder> certificatesStore = signedData.getCertificates();
    if (certificatesStore.getMatches(null).isEmpty()) {
        throw new IOException("No certificates in signature");
    }
    Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
    if (signers.isEmpty()) {
        throw new IOException("No signers in signature");
    }
    SignerInformation signerInformation = signers.iterator().next();
    @SuppressWarnings("unchecked") Collection<X509CertificateHolder> matches = certificatesStore.getMatches(signerInformation.getSID());
    if (matches.isEmpty()) {
        throw new IOException("Signer '" + signerInformation.getSID().getIssuer() + ", serial# " + signerInformation.getSID().getSerialNumber() + " does not match any certificates");
    }
    X509CertificateHolder certificateHolder = matches.iterator().next();
    X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    System.out.println("certFromSignedData: " + certFromSignedData);
    SigUtils.checkCertificateUsage(certFromSignedData);
    // Embedded timestamp
    TimeStampToken timeStampToken = SigUtils.extractTimeStampTokenFromSignerInformation(signerInformation);
    if (timeStampToken != null) {
        // tested with QV_RCA1_RCA3_CPCPS_V4_11.pdf
        // https://www.quovadisglobal.com/~/media/Files/Repository/QV_RCA1_RCA3_CPCPS_V4_11.ashx
        // also 021496.pdf and 036351.pdf from digitalcorpora
        SigUtils.validateTimestampToken(timeStampToken);
        X509Certificate certFromTimeStamp = SigUtils.getCertificateFromTimeStampToken(timeStampToken);
        // merge both stores using a set to remove duplicates
        HashSet<X509CertificateHolder> certificateHolderSet = new HashSet<>();
        certificateHolderSet.addAll(certificatesStore.getMatches(null));
        certificateHolderSet.addAll(timeStampToken.getCertificates().getMatches(null));
        SigUtils.verifyCertificateChain(new CollectionStore<>(certificateHolderSet), certFromTimeStamp, timeStampToken.getTimeStampInfo().getGenTime());
        SigUtils.checkTimeStampCertificateUsage(certFromTimeStamp);
        // compare the hash of the signature with the hash in the timestamp
        byte[] tsMessageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
        String hashAlgorithm = timeStampToken.getTimeStampInfo().getMessageImprintAlgOID().getId();
        byte[] sigMessageImprintDigest = MessageDigest.getInstance(hashAlgorithm).digest(signerInformation.getSignature());
        if (Arrays.equals(tsMessageImprintDigest, sigMessageImprintDigest)) {
            System.out.println("timestamp signature verified");
        } else {
            System.err.println("timestamp signature verification failed");
        }
    }
    try {
        if (sig.getSignDate() != null) {
            certFromSignedData.checkValidity(sig.getSignDate().getTime());
            System.out.println("Certificate valid at signing time");
        } else {
            System.err.println("Certificate cannot be verified without signing time");
        }
    } catch (CertificateExpiredException ex) {
        System.err.println("Certificate expired at signing time");
    } catch (CertificateNotYetValidException ex) {
        System.err.println("Certificate not yet valid at signing time");
    }
    // usually not available
    if (signerInformation.getSignedAttributes() != null) {
        // From SignedMailValidator.getSignatureTime()
        Attribute signingTime = signerInformation.getSignedAttributes().get(CMSAttributes.signingTime);
        if (signingTime != null) {
            Time timeInstance = Time.getInstance(signingTime.getAttrValues().getObjectAt(0));
            try {
                certFromSignedData.checkValidity(timeInstance.getDate());
                System.out.println("Certificate valid at signing time: " + timeInstance.getDate());
            } catch (CertificateExpiredException ex) {
                System.err.println("Certificate expired at signing time");
            } catch (CertificateNotYetValidException ex) {
                System.err.println("Certificate not yet valid at signing time");
            }
        }
    }
    if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(SecurityProvider.getProvider()).build(certFromSignedData))) {
        System.out.println("Signature verified");
    } else {
        System.out.println("Signature verification failed");
    }
    if (CertificateVerifier.isSelfSigned(certFromSignedData)) {
        System.err.println("Certificate is self-signed, LOL!");
    } else {
        System.out.println("Certificate is not self-signed");
        if (sig.getSignDate() != null) {
            SigUtils.verifyCertificateChain(certificatesStore, certFromSignedData, sig.getSignDate().getTime());
        } else {
            System.err.println("Certificate cannot be verified without signing time");
        }
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) Attribute(org.bouncycastle.asn1.cms.Attribute) SignerInformation(org.bouncycastle.cms.SignerInformation) Time(org.bouncycastle.asn1.x509.Time) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) IOException(java.io.IOException) COSString(org.apache.pdfbox.cos.COSString) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSProcessable(org.bouncycastle.cms.CMSProcessable) X509Certificate(java.security.cert.X509Certificate) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) HashSet(java.util.HashSet)

Aggregations

CMSProcessable (org.bouncycastle.cms.CMSProcessable)8 CMSSignedData (org.bouncycastle.cms.CMSSignedData)8 X509Certificate (java.security.cert.X509Certificate)5 SignerInformation (org.bouncycastle.cms.SignerInformation)5 JcaSimpleSignerInfoVerifierBuilder (org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder)5 IOException (java.io.IOException)4 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)4 CMSException (org.bouncycastle.cms.CMSException)4 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)3 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)3 PrivateKey (java.security.PrivateKey)2 CertificateException (java.security.cert.CertificateException)2 ParseException (java.text.ParseException)2 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)2 CMSSignerDigestMismatchException (org.bouncycastle.cms.CMSSignerDigestMismatchException)2 TSPException (org.bouncycastle.tsp.TSPException)2 CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)2 CertificateValidatorCRLException (org.demoiselle.signer.core.exception.CertificateValidatorCRLException)2 CertificateValidatorException (org.demoiselle.signer.core.exception.CertificateValidatorException)2 SignerException (org.demoiselle.signer.policy.impl.cades.SignerException)2