Search in sources :

Example 31 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project ats-framework by Axway.

the class SMimePackageEncryptor method checkSignature.

@SuppressWarnings("unchecked")
private boolean checkSignature(Package sourcePackage, String keystoreLocation, String keystorePassword, String keystoreAlias) throws ActionException {
    // for connection management to IMAP store
    boolean storeReconnected = false;
    if (sourcePackage instanceof MimePackage) {
        try {
            storeReconnected = ((MimePackage) sourcePackage).reconnectStoreIfClosed();
        } catch (MessagingException ex) {
            throw new ActionException("Could not reopen IMAP connection", ex);
        }
    }
    SMIMESigned signedMessage = getSMIMESignedMessage(sourcePackage);
    if (signedMessage == null) {
        throw new ActionException("The message is not signed");
    }
    try {
        // retrieve SignerInformation blocks which contains the signatures
        SignerInformationStore signers = signedMessage.getSignerInfos();
        Iterator<SignerInformation> it = signers.getSigners().iterator();
        if (keystoreLocation == null) {
            // extract public keys from the signature
            // a Store containing the public key certificates passed in the signature
            Store<?> certs = signedMessage.getCertificates();
            // Note: mail could be signed by multiple users. Currently we search for one/first signature match
            while (it.hasNext()) {
                SignerInformation signer = it.next();
                // extract the certificate for current signature - with first certificate only
                Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator();
                X509Certificate cert = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate((X509CertificateHolder) certIt.next());
                // verify that the signature is correct and generated with the current certificate
                if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert))) {
                    return true;
                }
            }
            LOG.debug("No suitable public key found in the signature to verify it.");
        } else {
            // load public key from the certificate store file
            KeyStore ks;
            ks = KeyStore.getInstance(PKCS12_KEYSTORE_TYPE, BouncyCastleProvider.PROVIDER_NAME);
            ks.load(new FileInputStream(keystoreLocation), keystorePassword.toCharArray());
            String keyAlias = null;
            if (keystoreAlias == null) {
                Enumeration<String> aliases = ks.aliases();
                keyAlias = aliases.nextElement();
            } else {
                keyAlias = keystoreAlias;
            }
            while (it.hasNext()) {
                X509Certificate cert = (X509Certificate) ks.getCertificate(keyAlias);
                Key publicKey = cert.getPublicKey();
                if (publicKey == null) {
                    throw new Exception("The key for alias '" + keyAlias + "' was not found in keystore '" + keystoreLocation + "'");
                }
                // verify that the signature is correct and generated with the provided certificate
                if (it.next().verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert))) {
                    return true;
                }
            }
            LOG.debug("Could not verify the signature with the public key alias: " + keyAlias);
        }
        return false;
    } catch (Exception e) {
        throw new ActionException(SIGNATURE_EXCEPTION, e);
    } finally {
        if (storeReconnected) {
            // and sourcePackage should be instanceof MimePackage
            try {
                ((MimePackage) sourcePackage).closeStoreConnection(false);
            } catch (MessagingException ex) {
                // do not hide possible exception thrown in catch block
                LOG.debug(ex);
            }
        }
    }
}
Also used : SMIMESigned(org.bouncycastle.mail.smime.SMIMESigned) MessagingException(javax.mail.MessagingException) ActionException(com.axway.ats.action.model.ActionException) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) MessagingException(javax.mail.MessagingException) ActionException(com.axway.ats.action.model.ActionException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) MimePackage(com.axway.ats.action.objects.MimePackage) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) Key(java.security.Key) PrivateKey(java.security.PrivateKey)

Example 32 with SignerInformation

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

SignerInformation (org.bouncycastle.cms.SignerInformation)32 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)21 CMSSignedData (org.bouncycastle.cms.CMSSignedData)19 X509Certificate (java.security.cert.X509Certificate)17 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)13 JcaSimpleSignerInfoVerifierBuilder (org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder)13 CMSException (org.bouncycastle.cms.CMSException)10 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)8 CertificateException (java.security.cert.CertificateException)7 Attribute (org.bouncycastle.asn1.cms.Attribute)7 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)7 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)7 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)6 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)6 FileInputStream (java.io.FileInputStream)4 CertStore (java.security.cert.CertStore)4 Date (java.util.Date)4