Search in sources :

Example 31 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource 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 32 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource 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 33 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.

the class NotificationTest method testCreateNotification_AssertInputStream.

public void testCreateNotification_AssertInputStream() throws Exception {
    Notification noti = new Notification(NotificationType.Processed);
    ByteArrayDataSource dataSource = new ByteArrayDataSource(noti.getInputStream(), noti.getAsMultipart().getContentType());
    MimeMultipart mm = new MimeMultipart(dataSource);
    assertNotNull(mm);
    assertEquals(2, mm.getCount());
    BodyPart part = mm.getBodyPart(0);
    assertTrue(part.getContentType().startsWith("text/plain"));
    assertEquals("Your message was successfully processed.", part.getContent().toString());
    part = mm.getBodyPart(1);
    assertTrue(part.getContentType().startsWith("message/disposition-notification"));
    DispositionNotification notification = (DispositionNotification) part.getContent();
    assertEquals(notification.getNotifications().getHeader("disposition", ","), "automatic-action/MDN-sent-automatically;processed");
}
Also used : BodyPart(javax.mail.BodyPart) DispositionNotification(com.sun.mail.dsn.DispositionNotification) MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DispositionNotification(com.sun.mail.dsn.DispositionNotification)

Example 34 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project zm-mailbox by Zimbra.

the class Mime method fixBase64MimePartLineFolding.

/**
     * Some devices send wide base64 encoded message body i.e. without line folding.
     * As per RFC https://www.ietf.org/rfc/rfc2045.txt see 6.8.  Base64 Content-Transfer-Encoding
     * "The encoded output stream must be represented in lines of no more than 76 characters each."
     * 
     * To fix the issue here, re-writing the same content to message part.
     * @param mm
     * @throws MessagingException
     * @throws IOException
     */
public static void fixBase64MimePartLineFolding(MimeMessage mm) throws MessagingException, IOException {
    List<MPartInfo> mList = Mime.getParts(mm);
    for (MPartInfo mPartInfo : mList) {
        String ct = mPartInfo.getMimePart().getHeader("Content-Transfer-Encoding", ":");
        if (MimeConstants.ET_BASE64.equalsIgnoreCase(ct)) {
            InputStream io = mPartInfo.getMimePart().getInputStream();
            String ctype = mPartInfo.getMimePart().getContentType();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(io, bos);
            DataSource ds = new ByteArrayDataSource(bos.toByteArray(), ctype);
            DataHandler dh = new DataHandler(ds);
            mPartInfo.getMimePart().setDataHandler(dh);
            mPartInfo.getMimePart().setHeader("Content-Transfer-Encoding", ct);
            mPartInfo.getMimePart().setHeader("Content-Type", ctype);
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PipedInputStream(java.io.PipedInputStream) SharedFileInputStream(javax.mail.util.SharedFileInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource)

Example 35 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project zm-mailbox by Zimbra.

the class MessageBuilder method create.

public String create() throws MessagingException, ServiceException, IOException {
    if (toRecipient == null) {
        toRecipient = "user1";
    }
    if (from == null) {
        from = "jspiccoli";
    }
    if (date == null) {
        date = new Date();
    }
    if (contentType == null) {
        contentType = MimeConstants.CT_TEXT_PLAIN;
    }
    if (body == null) {
        body = MessageBuilder.DEFAULT_MESSAGE_BODY;
    }
    from = TestUtil.addDomainIfNecessary(from);
    toRecipient = TestUtil.addDomainIfNecessary(toRecipient);
    sender = TestUtil.addDomainIfNecessary(sender);
    MimeMessage msg = addMessageIdHeader ? new ZMimeMessage(JMSession.getSession()) : new MimeMessageWithNoId();
    msg.setRecipient(RecipientType.TO, new JavaMailInternetAddress(toRecipient));
    if (ccRecipient != null) {
        ccRecipient = TestUtil.addDomainIfNecessary(ccRecipient);
        msg.setRecipient(RecipientType.CC, new JavaMailInternetAddress(ccRecipient));
    }
    msg.setFrom(new JavaMailInternetAddress(from));
    if (sender != null) {
        msg.setSender(new JavaMailInternetAddress(sender));
    }
    msg.setSentDate(date);
    msg.setSubject(subject);
    if (attachment == null) {
        // Need to specify the data handler explicitly because JavaMail
        // doesn't know what to do with text/enriched.
        msg.setDataHandler(new DataHandler(new ByteArrayDataSource(body.getBytes(), contentType)));
    } else {
        MimeMultipart multi = new ZMimeMultipart("mixed");
        MimeBodyPart body = new ZMimeBodyPart();
        body.setDataHandler(new DataHandler(new ByteArrayDataSource(this.body.getBytes(), contentType)));
        multi.addBodyPart(body);
        MimeBodyPart attachment = new ZMimeBodyPart();
        attachment.setContent(this.attachment, attachmentContentType);
        attachment.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
        multi.addBodyPart(attachment);
        msg.setContent(multi);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    return new String(out.toByteArray());
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Date(java.util.Date) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Aggregations

ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)40 DataHandler (javax.activation.DataHandler)27 MimeMultipart (javax.mail.internet.MimeMultipart)18 IOException (java.io.IOException)16 DataSource (javax.activation.DataSource)15 MessagingException (javax.mail.MessagingException)14 MimeBodyPart (javax.mail.internet.MimeBodyPart)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 ByteArrayInputStream (java.io.ByteArrayInputStream)9 InputStream (java.io.InputStream)9 ArrayList (java.util.ArrayList)9 MimeMessage (javax.mail.internet.MimeMessage)7 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)5 List (java.util.List)5 Test (org.junit.Test)5 ContentDisposition (com.zimbra.common.mime.ContentDisposition)4 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)4 Document (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document)4 Exchange (org.apache.camel.Exchange)3 ByteString (com.linkedin.data.ByteString)2