Search in sources :

Example 16 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.

the class SMIMECryptographerImpl method checkSignature.

//-----------------------------------------------------
//
// Signature Validation
//
//-----------------------------------------------------
/**
     * Validates that a signed entity has a valid message and signature.  The signer's certificate is validated to ensure authenticity of the message.  Message
     * tampering is also checked with the message's digest and the signed digest in the message signature.
     * @param signedEntity The entity containing the original signed part and the message signature.
     * @param signerCertificate The certificate used to sign the message.
     * @param anchors A collection of certificate anchors used to determine if the certificates used in the signature can be validated as trusted certificates.
     */
public void checkSignature(SignedEntity signedEntity, X509Certificate signerCertificate, Collection<X509Certificate> anchors) throws SignatureValidationException {
    CMSSignedData signatureEnvelope = deserializeSignatureEnvelope(signedEntity);
    SignerInformation logSigInfo = null;
    try {
        // is verified with the signerCertificate
        for (SignerInformation sigInfo : (Collection<SignerInformation>) signatureEnvelope.getSignerInfos().getSigners()) {
            logSigInfo = sigInfo;
            // such as MD5
            if (!isAllowedDigestAlgorithm(sigInfo.getDigestAlgOID()))
                throw new SignatureValidationException("Digest algorithm " + sigInfo.getDigestAlgOID() + " is not allowed.");
            if (sigInfo.verify(signerCertificate, CryptoExtensions.getJCEProviderName())) {
                // verified... return
                return;
            }
        }
        // at this point the signerCertificate cannot be verified with one of the signing certificates....
        throw new SignatureValidationException("Signature validation failure.");
    } catch (SignatureValidationException sve) {
        throw sve;
    } catch (Exception e) {
        throw new SignatureValidationException("Signature validation failure.", e);
    } finally {
        logDigests(logSigInfo);
    }
}
Also used : Collection(java.util.Collection) SignerInformation(org.bouncycastle.cms.SignerInformation) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) MessagingException(javax.mail.MessagingException) MimeException(org.nhindirect.stagent.mail.MimeException) NHINDException(org.nhindirect.stagent.NHINDException) ParseException(javax.mail.internet.ParseException) IOException(java.io.IOException) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException)

Example 17 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.

the class SMIMECryptographerImpl_createSignatureEntityTest method validateSignature.

@SuppressWarnings("unchecked")
protected void validateSignature(CMSSignedData data, X509Certificate signerCert) throws Exception {
    assertNotNull(data);
    assertEquals(1, data.getSignerInfos().getSigners().size());
    for (SignerInformation sigInfo : (Collection<SignerInformation>) data.getSignerInfos().getSigners()) {
        assertTrue(sigInfo.verify(signerCert, CryptoExtensions.getJCEProviderName()));
        /*
    		 * explicit hash algorithm checking for compliance with Applicability
    		 * Statement v 1.2
    		 */
        assertEquals(DigestAlgorithm.SHA256.getOID(), sigInfo.getDigestAlgOID());
    }
}
Also used : Collection(java.util.Collection) SignerInformation(org.bouncycastle.cms.SignerInformation)

Example 18 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.

the class DefaultBundleRefreshProcessorImpl method convertRawBundleToAnchorCollection.

/**
	 * Converts a trust raw trust bundle byte array into a collection of {@link X509Certificate} objects.
	 * @param rawBundle The raw representation of the bundle.  This generally the raw byte string downloaded from the bundle's URL.
	 * @param existingBundle The configured bundle object in the DAO.  This object may contain the signing certificate
	 * used for bundle authenticity checking.
	 * @param processAttempStart The time that the update process started.
	 * @return
	 */
@SuppressWarnings("unchecked")
protected Collection<X509Certificate> convertRawBundleToAnchorCollection(byte[] rawBundle, final TrustBundle existingBundle, final Calendar processAttempStart) {
    Collection<? extends Certificate> bundleCerts = null;
    InputStream inStream = null;
    // check to see if its an unsigned PKCS7 container
    try {
        inStream = new ByteArrayInputStream(rawBundle);
        bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
        // if its null and has no anchors, then try again as a signed bundle
        if (bundleCerts != null && bundleCerts.size() == 0)
            bundleCerts = null;
    } catch (Exception e) {
    /* no-op for now.... this may not be a p7b, so try it as a signed message*/
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    // didnt work... try again as a CMS signed message
    if (bundleCerts == null) {
        try {
            final CMSSignedData signed = new CMSSignedData(rawBundle);
            // then verify the signature
            if (existingBundle.getSigningCertificateData() != null) {
                boolean sigVerified = false;
                final X509Certificate signingCert = existingBundle.toSigningCertificate();
                for (SignerInformation sigInfo : (Collection<SignerInformation>) signed.getSignerInfos().getSigners()) {
                    try {
                        if (sigInfo.verify(signingCert, CryptoExtensions.getJCEProviderName())) {
                            sigVerified = true;
                            break;
                        }
                    } catch (Exception e) {
                    /* no-op... can't verify */
                    }
                }
                if (!sigVerified) {
                    dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.UNMATCHED_SIGNATURE);
                    log.warn("Downloaded bundle signature did not match configured signing certificate.");
                    return null;
                }
            }
            final CMSProcessableByteArray signedContent = (CMSProcessableByteArray) signed.getSignedContent();
            inStream = new ByteArrayInputStream((byte[]) signedContent.getContent());
            bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
        } catch (Exception e) {
            dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.INVALID_BUNDLE_FORMAT);
            log.warn("Failed to extract anchors from downloaded bundle at URL " + existingBundle.getBundleURL());
        } finally {
            IOUtils.closeQuietly(inStream);
        }
    }
    return (Collection<X509Certificate>) bundleCerts;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Collection(java.util.Collection) SignerInformation(org.bouncycastle.cms.SignerInformation) CMSSignedData(org.bouncycastle.cms.CMSSignedData) SocketTimeoutException(java.net.SocketTimeoutException) ConfigurationStoreException(org.nhindirect.config.store.ConfigurationStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate)

Example 19 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.

the class SigTest method testCreateVerifySig.

public void testCreateVerifySig() throws Exception {
    X509CertificateEx internalCert = TestUtils.getInternalCert("user1");
    X509Certificate caCert = TestUtils.getExternalCert("cacert");
    String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
    MimeMessage entity = EntitySerializer.Default.deserialize(testMessage);
    Message message = new Message(entity);
    MimeEntity entityToSig = message.extractEntityForSignature(true);
    // Serialize message out as ASCII encoded...
    byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entityToSig);
    MimeBodyPart partToSign = null;
    try {
        partToSign = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
    } catch (Exception e) {
    }
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);
    caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
    caps.addCapability(PKCSObjectIdentifiers.x509Certificate);
    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    List certList = new ArrayList();
    gen.addSigner(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
    //SMIMESignedGenerator.DIGEST_SHA1, null, null);
    certList.add(internalCert);
    MimeMultipart retVal = null;
    CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderName());
    gen.addCertificatesAndCRLs(certsAndcrls);
    _certStores.add(certsAndcrls);
    _signers.add(new Signer(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null));
    retVal = generate(partToSign, CryptoExtensions.getJCEProviderName());
    for (int i = 0; i < 10; ++i) {
        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
        retVal.writeTo(oStream);
        oStream.flush();
        byte[] serialzedBytes = oStream.toByteArray();
        //System.out.println(new String(serialzedBytes, "ASCII") + "\r\n\r\n\r\n\r\n\r\n");
        ByteArrayDataSource dataSource = new ByteArrayDataSource(serialzedBytes, retVal.getContentType());
        MimeMultipart verifyMM = new MimeMultipart(dataSource);
        CMSSignedData signed = null;
        //CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(verifyMM.getBodyPart(0)), verifyMM.getBodyPart(1).getInputStream());			
        CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(partToSign), verifyMM.getBodyPart(1).getInputStream());
        int verified = 0;
        CertStore certs = signeddata.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
        SignerInformationStore signers = signeddata.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());
            Attribute dig = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
            DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject();
            byte[] signedHash = ((ASN1OctetString) hashObj).getOctets();
            System.out.print("value of signedHash: \r\n\tvalue: ");
            for (byte bt : signedHash) {
                System.out.print(bt + " ");
            }
            System.out.println();
            Iterator certIt = certCollection.iterator();
            try {
                assertTrue(signer.verify(internalCert, CryptoExtensions.getJCEProviderName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            byte[] bytes = signer.getContentDigest();
            /*
	    		  X509Certificate cert = (X509Certificate)certIt.next();
	    		  
    		      if (signer.verify(cert.getPublicKey()))
    		      {
    		          verified++;
    		      }
	    		  */
            verified++;
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CMSProcessableBodyPartInbound(org.bouncycastle.mail.smime.CMSProcessableBodyPartInbound) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Attribute(org.bouncycastle.asn1.cms.Attribute) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ArrayList(java.util.ArrayList) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) SMIMESignedGenerator(org.bouncycastle.mail.smime.SMIMESignedGenerator) SignerInformation(org.bouncycastle.cms.SignerInformation) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) DERObject(org.bouncycastle.asn1.DERObject) MimeMessage(javax.mail.internet.MimeMessage) SMIMECapabilityVector(org.bouncycastle.asn1.smime.SMIMECapabilityVector) MimeMultipart(javax.mail.internet.MimeMultipart) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) Iterator(java.util.Iterator) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) CertStoreException(java.security.cert.CertStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CMSException(org.bouncycastle.cms.CMSException) IOException(java.io.IOException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) NoSuchProviderException(java.security.NoSuchProviderException) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) Collection(java.util.Collection) MimeBodyPart(javax.mail.internet.MimeBodyPart) CertStore(java.security.cert.CertStore)

Example 20 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.

the class CryptoExtensions method findSignerByCert.

/**
	 * Searches CMS signed data for a specific X509 certificate.
	 * @param signedData The signed data to search.
	 * @param name The certificate to search for in the signed data.
	 * @return A pair consisting of the singer's X509 certificated and signer information that matches the provided certificate.  Returns
	 * null if a signer matching the name cannot be found in the signed data.
	 */
public static SignerCertPair findSignerByCert(CMSSignedData signedData, X509Certificate searchCert) {
    if (searchCert == null) {
        throw new IllegalArgumentException();
    }
    try {
        SignerInformationStore signers = signedData.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        for (SignerInformation signer : c) {
            //signer.getSID().
            SignerId signerId = signer.getSID();
            if (signerId.getIssuer().equals(searchCert.getIssuerX500Principal()) && signerId.getSerialNumber().equals(searchCert.getSerialNumber())) {
                return new SignerCertPair(signer, searchCert);
            }
        }
    } catch (Exception e) {
    }
    return null;
}
Also used : SignerCertPair(org.nhindirect.stagent.cert.SignerCertPair) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) SignerId(org.bouncycastle.cms.SignerId) SignerInformation(org.bouncycastle.cms.SignerInformation) CertificateParsingException(java.security.cert.CertificateParsingException) CertificateException(java.security.cert.CertificateException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

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