Search in sources :

Example 36 with CMSSignedData

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

the class DefaultNHINDAgent method decryptSignedContent.

/*
     * Decrypts the signed message
     */
@SuppressWarnings("unchecked")
protected void decryptSignedContent(IncomingMessage message) {
    MimeEntity decryptedEntity = this.decryptMessage(message);
    CMSSignedData signatures;
    MimeEntity payload;
    try {
        if (SMIMEStandard.isContentEnvelopedSignature(new ContentType(decryptedEntity.getContentType()))) {
            signatures = cryptographer.deserializeEnvelopedSignature(decryptedEntity);
            payload = new MimeEntity(new ByteArrayInputStream(signatures.getContentInfo().getEncoded()));
        } else if (SMIMEStandard.isContentMultipartSignature(new ContentType(decryptedEntity.getContentType()))) {
            //
            // Extract the signature envelope. That contains both the signature and the actual message content
            //
            ByteArrayDataSource dataSource = new ByteArrayDataSource(decryptedEntity.getRawInputStream(), decryptedEntity.getContentType());
            MimeMultipart verifyMM = new MimeMultipart(dataSource);
            SignedEntity signedEntity = SignedEntity.load(verifyMM);
            signatures = cryptographer.deserializeSignatureEnvelope(signedEntity);
            payload = signedEntity.getContent();
        } else {
            throw new AgentException(AgentError.UnsignedMessage);
        }
        message.setSignature(signatures);
        //
        // Alter body to contain actual content. Also clean up mime headers on the message that were there to support
        // signatures etc
        //         	
        InternetHeaders headers = new InternetHeaders();
        // remove all mime headers
        Enumeration<Header> eHeaders = message.getMessage().getAllHeaders();
        while (eHeaders.hasMoreElements()) {
            Header hdr = (Header) eHeaders.nextElement();
            if (!MimeStandard.startsWith(hdr.getName(), MimeStandard.HeaderPrefix))
                headers.setHeader(hdr.getName(), hdr.getValue());
        }
        // add back in headers from original message
        eHeaders = payload.getAllHeaders();
        while (eHeaders.hasMoreElements()) {
            Header hdr = (Header) eHeaders.nextElement();
            headers.setHeader(hdr.getName(), hdr.getValue());
        }
        Message msg = new Message(headers, payload.getContentAsBytes());
        message.setMessage(msg);
    } catch (MessagingException e) {
        throw new MimeException(MimeError.InvalidBody, e);
    } catch (IOException e) {
        throw new MimeException(MimeError.InvalidBody, e);
    }
}
Also used : ContentType(javax.mail.internet.ContentType) InternetHeaders(javax.mail.internet.InternetHeaders) WrappedMessage(org.nhindirect.stagent.mail.WrappedMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) Header(javax.mail.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) MimeException(org.nhindirect.stagent.mail.MimeException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) SignedEntity(org.nhindirect.stagent.cryptography.SignedEntity)

Example 37 with CMSSignedData

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

the class CryptographerTest method testvalidateSignature.

public void testvalidateSignature() throws Exception {
    final String str = FileUtils.readFileToString(new File("./src/test/resources/org/nhindirect/stagent/msgSig.txt"));
    byte[] byteData = Base64.decode(str);
    CMSSignedData signed = new CMSSignedData(byteData);
    CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
    Collection<? extends Certificate> certCollection = certs.getCertificates(null);
    for (Certificate cert : certCollection) {
        FileUtils.writeByteArrayToFile(new File("./testCert.der"), cert.getEncoded());
    }
}
Also used : File(java.io.File) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 38 with CMSSignedData

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

the class SMIMECryptographerImpl_createSignatureEntityTest method deserializeSignatureEnvelope.

protected CMSSignedData deserializeSignatureEnvelope(MimeMultipart mm) throws Exception {
    final MimeEntity contentEntity = contentToMimeEntity(mm.getBodyPart(0));
    byte[] messageBytes = EntitySerializer.Default.serializeToBytes(contentEntity);
    MimeBodyPart signedContent = null;
    signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
    return new CMSSignedData(new CMSProcessableBodyPart(signedContent), mm.getBodyPart(1).getInputStream());
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) MimeBodyPart(javax.mail.internet.MimeBodyPart) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSProcessableBodyPart(org.bouncycastle.mail.smime.CMSProcessableBodyPart)

Example 39 with CMSSignedData

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

the class TrustModel_findTrustedSignatureTest method setUp.

@Override
public void setUp() throws Exception {
    CryptoExtensions.registerJCEProviders();
    // load sigCert A
    sigUser1 = TestUtils.getInternalCert("user1");
    // load sigCert A private certificate
    sigUser1CA = TestUtils.getInternalCACert("cacert");
    // load other anchor
    otherCert = TestUtils.loadCertificate("gm2552.der");
    // load the message that will be encrypted
    String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
    cryptographer = new SMIMECryptographerImpl();
    inMessage = new IncomingMessage(new Message(new ByteArrayInputStream(testMessage.getBytes())));
    signedEntity = cryptographer.sign(inMessage.getMessage(), sigUser1);
    CMSSignedData signatures = cryptographer.deserializeSignatureEnvelope(signedEntity);
    inMessage.setSignature(signatures);
}
Also used : Message(org.nhindirect.stagent.mail.Message) IncomingMessage(org.nhindirect.stagent.IncomingMessage) SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) IncomingMessage(org.nhindirect.stagent.IncomingMessage) ByteArrayInputStream(java.io.ByteArrayInputStream) CMSSignedData(org.bouncycastle.cms.CMSSignedData)

Example 40 with CMSSignedData

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

Aggregations

CMSSignedData (org.bouncycastle.cms.CMSSignedData)68 X509Certificate (java.security.cert.X509Certificate)32 IOException (java.io.IOException)31 CMSException (org.bouncycastle.cms.CMSException)31 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)22 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)20 SignerInformation (org.bouncycastle.cms.SignerInformation)19 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)17 ArrayList (java.util.ArrayList)16 JcaCertStore (org.bouncycastle.cert.jcajce.JcaCertStore)15 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)15 ByteArrayInputStream (java.io.ByteArrayInputStream)13 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)12 JcaSignerInfoGeneratorBuilder (org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder)12 CertificateException (java.security.cert.CertificateException)9 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)9 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)9 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)9 ContentSigner (org.bouncycastle.operator.ContentSigner)9 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)9