Search in sources :

Example 16 with MimeEntity

use of org.nhindirect.stagent.mail.MimeEntity in project nhin-d by DirectProject.

the class DefaultNHINDAgent method signAndEncryptMessage.

//
// First sign, THEN encrypt the message
//
@SuppressWarnings("unchecked")
protected void signAndEncryptMessage(OutgoingMessage message) {
    SignedEntity signedEntity = cryptographer.sign(message.getMessage(), message.getSender().getCertificates());
    try {
        if (encryptionEnabled) {
            MimeEntity encryptedEntity = cryptographer.encrypt(signedEntity.getMimeMultipart(), message.getRecipients().getCertificates());
            //
            // Alter message content to contain encrypted data
            //
            InternetHeaders headers = new InternetHeaders();
            Enumeration<Header> eHeaders = message.getMessage().getAllHeaders();
            while (eHeaders.hasMoreElements()) {
                Header hdr = eHeaders.nextElement();
                headers.setHeader(hdr.getName(), hdr.getValue());
            }
            eHeaders = encryptedEntity.getAllHeaders();
            while (eHeaders.hasMoreElements()) {
                Header hdr = (Header) eHeaders.nextElement();
                headers.setHeader(hdr.getName(), hdr.getValue());
            }
            Message msg = new Message(headers, encryptedEntity.getContentAsBytes());
            message.setMessage(msg);
        } else {
            InternetHeaders headers = new InternetHeaders();
            Enumeration<Header> eHeaders = message.getMessage().getAllHeaders();
            while (eHeaders.hasMoreElements()) {
                Header hdr = eHeaders.nextElement();
                headers.setHeader(hdr.getName(), hdr.getValue());
            }
            headers.setHeader(MimeStandard.ContentTypeHeader, signedEntity.getMimeMultipart().getContentType());
            Message msg = new Message(headers, signedEntity.getEntityBodyAsBytes());
            message.setMessage(msg);
        }
    } catch (Exception e) {
        throw new MimeException(MimeError.InvalidMimeEntity, e);
    }
}
Also used : InternetHeaders(javax.mail.internet.InternetHeaders) Header(javax.mail.Header) WrappedMessage(org.nhindirect.stagent.mail.WrappedMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) MimeException(org.nhindirect.stagent.mail.MimeException) SignedEntity(org.nhindirect.stagent.cryptography.SignedEntity) MessagingException(javax.mail.MessagingException) TrustException(org.nhindirect.stagent.trust.TrustException) MimeException(org.nhindirect.stagent.mail.MimeException) PolicyRequiredException(org.nhindirect.policy.PolicyRequiredException) PolicyParseException(org.nhindirect.policy.PolicyParseException) IOException(java.io.IOException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException)

Example 17 with MimeEntity

use of org.nhindirect.stagent.mail.MimeEntity 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 18 with MimeEntity

use of org.nhindirect.stagent.mail.MimeEntity in project nhin-d by DirectProject.

the class CryptographerTest method testEncryptAndDecryptMimeEntity_hsmDecryption.

private void testEncryptAndDecryptMimeEntity_hsmDecryption(EncryptionAlgorithm encAlg) throws Exception {
    OptionsManager.destroyInstance();
    CryptoExtensions.registerJCEProviders();
    try {
        final PKCS11Credential cred = new BootstrappedPKCS11Credential("1Kingpuff");
        final MutableKeyStoreProtectionManager mgr = new StaticPKCS11TokenKeyStoreProtectionManager(cred, "", "");
        final CacheableKeyStoreManagerCertificateStore store = new CacheableKeyStoreManagerCertificateStore(mgr);
        store.add(TestUtils.getInternalCert("user1"));
        X509Certificate cert = TestUtils.getExternalCert("user1");
        SMIMECryptographerImpl cryptographer = new SMIMECryptographerImpl();
        cryptographer.setRecipientInformationFactory(new SplitDirectRecipientInformationFactory(pkcs11ProviderName, ""));
        cryptographer.setEncryptionAlgorithm(encAlg);
        MimeEntity entity = new MimeEntity();
        entity.setText("Hello world.");
        entity.setHeader(MimeStandard.ContentTypeHeader, "text/plain");
        entity.setHeader(MimeStandard.ContentTransferEncodingHeader, "7bit");
        MimeEntity encEntity = cryptographer.encrypt(entity, cert);
        assertNotNull(encEntity);
        // open up the pkcs11 store and find the private key
        KeyStore ks = KeyStore.getInstance("PKCS11");
        ks.load(null, "1Kingpuff".toCharArray());
        X509CertificateEx decryptCert = null;
        final Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            Certificate pkcs11Cert = ks.getCertificate(alias);
            if (pkcs11Cert != null && pkcs11Cert instanceof X509Certificate) {
                // check if there is private key
                Key key = ks.getKey(alias, null);
                if (key != null && key instanceof PrivateKey && CryptoExtensions.certSubjectContainsName((X509Certificate) pkcs11Cert, "user1@cerner.com")) {
                    decryptCert = X509CertificateEx.fromX509Certificate((X509Certificate) pkcs11Cert, (PrivateKey) key);
                    break;
                }
            }
        }
        MimeEntity decryEntity = cryptographer.decrypt(encEntity, decryptCert);
        assertNotNull(decryEntity);
        byte[] decryEntityBytes = EntitySerializer.Default.serializeToBytes(decryEntity);
        byte[] entityBytes = EntitySerializer.Default.serializeToBytes(entity);
        assertTrue(Arrays.equals(decryEntityBytes, entityBytes));
    } finally {
        System.setProperty("org.nhindirect.stagent.cryptography.JCESensitiveProviderName", "");
        System.setProperty("org.nhindirect.stagent.cryptography.JCESensitiveProviderClassNames", "");
        OptionsManager.destroyInstance();
    }
}
Also used : PKCS11Credential(org.nhindirect.common.crypto.PKCS11Credential) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential) PrivateKey(java.security.PrivateKey) SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) SplitDirectRecipientInformationFactory(org.nhindirect.stagent.cryptography.activekeyops.SplitDirectRecipientInformationFactory) CacheableKeyStoreManagerCertificateStore(org.nhindirect.stagent.cert.impl.CacheableKeyStoreManagerCertificateStore) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) StaticPKCS11TokenKeyStoreProtectionManager(org.nhindirect.common.crypto.impl.StaticPKCS11TokenKeyStoreProtectionManager) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 19 with MimeEntity

use of org.nhindirect.stagent.mail.MimeEntity in project nhin-d by DirectProject.

the class CryptographerTest method testSignMimeEntity_SHA256Digest_forceStrongDigest_assertValidation.

public void testSignMimeEntity_SHA256Digest_forceStrongDigest_assertValidation() throws Exception {
    X509CertificateEx certex = TestUtils.getInternalCert("user1");
    SMIMECryptographerImpl cryptographer = new SMIMECryptographerImpl();
    cryptographer.setDigestAlgorithm(DigestAlgorithm.SHA256);
    MimeEntity entity = new MimeEntity();
    entity.setText("Hello world.");
    entity.setHeader(MimeStandard.ContentTypeHeader, "text/plain");
    entity.setHeader(MimeStandard.ContentTransferEncodingHeader, "7bit");
    SignedEntity signedEnt = cryptographer.sign(entity, certex);
    assertNotNull(signedEnt);
    byte[] signedEntityBytes = EntitySerializer.Default.serializeToBytes(signedEnt.getContent());
    byte[] entityBytes = EntitySerializer.Default.serializeToBytes(entity);
    assertTrue(Arrays.equals(signedEntityBytes, entityBytes));
    assertNotNull(signedEnt.getSignature());
    X509Certificate cert = TestUtils.getExternalCert("user1");
    cryptographer.checkSignature(signedEnt, cert, new ArrayList<X509Certificate>());
}
Also used : X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) SignedEntity(org.nhindirect.stagent.cryptography.SignedEntity) X509Certificate(java.security.cert.X509Certificate)

Example 20 with MimeEntity

use of org.nhindirect.stagent.mail.MimeEntity in project nhin-d by DirectProject.

the class CryptographerTest method testEncryptAndSignMimeEntity.

public void testEncryptAndSignMimeEntity() throws Exception {
    X509Certificate cert = TestUtils.getInternalCACert("user1");
    SMIMECryptographerImpl cryptographer = new SMIMECryptographerImpl();
    MimeEntity entity = new MimeEntity();
    entity.setText("Hello world.");
    entity.setHeader(MimeStandard.ContentTypeHeader, "text/plain");
    entity.setHeader(MimeStandard.ContentTransferEncodingHeader, "7bit");
    MimeEntity encEntity = cryptographer.encrypt(entity, cert);
    assertNotNull(encEntity);
    X509CertificateEx certex = TestUtils.getInternalCert("user1");
    SignedEntity signedEnt = cryptographer.sign(entity, certex);
    assertNotNull(signedEnt);
    cryptographer.checkSignature(signedEnt, cert, new ArrayList<X509Certificate>());
}
Also used : SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) SignedEntity(org.nhindirect.stagent.cryptography.SignedEntity) X509Certificate(java.security.cert.X509Certificate)

Aggregations

MimeEntity (org.nhindirect.stagent.mail.MimeEntity)34 X509Certificate (java.security.cert.X509Certificate)20 X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)18 SMIMECryptographerImpl (org.nhindirect.stagent.cryptography.SMIMECryptographerImpl)17 ByteArrayInputStream (java.io.ByteArrayInputStream)10 MessagingException (javax.mail.MessagingException)9 IOException (java.io.IOException)8 MimeMultipart (javax.mail.internet.MimeMultipart)8 SignedEntity (org.nhindirect.stagent.cryptography.SignedEntity)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 Message (org.nhindirect.stagent.mail.Message)6 MimeException (org.nhindirect.stagent.mail.MimeException)6 ArrayList (java.util.ArrayList)5 InternetHeaders (javax.mail.internet.InternetHeaders)5 SMIMEEnveloped (org.bouncycastle.mail.smime.SMIMEEnveloped)5 NHINDException (org.nhindirect.stagent.NHINDException)5 SignatureValidationException (org.nhindirect.stagent.SignatureValidationException)5 KeyStore (java.security.KeyStore)3 MimeBodyPart (javax.mail.internet.MimeBodyPart)3 MimeMessage (javax.mail.internet.MimeMessage)3