Search in sources :

Example 56 with ByteArrayDataSource

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

the class TestContacts method testServerAttachment.

/**
     * Tests the server-side {@link Attachment} class.
     */
@Test
public void testServerAttachment() throws Exception {
    // Specify the attachment size.
    byte[] data = "test".getBytes();
    ByteArrayDataSource ds = new ByteArrayDataSource(data, "text/plain");
    ds.setName("attachment.txt");
    DataHandler dh = new DataHandler(ds);
    Attachment attach = new Attachment(dh, "attachment", data.length);
    // Don't specify the attachment size.
    attach = new Attachment(dh, "attachment");
    checkServerAttachment(data, attach);
    // Create attachment from byte[].
    attach = new Attachment(data, "text/plain", "attachment", "attachment.txt");
    checkServerAttachment(data, attach);
}
Also used : Attachment(com.zimbra.cs.mailbox.Contact.Attachment) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Test(org.junit.Test)

Example 57 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 58 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 59 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 60 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project webservices-axiom by apache.

the class AttachmentsTest method testReadBase64EncodedAttachment.

private void testReadBase64EncodedAttachment(boolean useFile) throws Exception {
    // Note: We are only interested in the MimeMultipart, but we need to create a
    //       MimeMessage to be able to calculate the correct content type
    MimeMessage message = new MimeMessage((Session) null);
    MimeMultipart mp = new MimeMultipart("related");
    // Prepare the "SOAP" part
    MimeBodyPart bp1 = new MimeBodyPart();
    // Obviously this is not SOAP, but this is irrelevant for this test
    bp1.setText("<root/>", "utf-8", "xml");
    bp1.addHeader("Content-Transfer-Encoding", "binary");
    bp1.addHeader("Content-ID", "part1@apache.org");
    mp.addBodyPart(bp1);
    // Prepare the attachment
    MimeBodyPart bp2 = new MimeBodyPart();
    byte[] content = new byte[8192];
    new Random().nextBytes(content);
    bp2.setDataHandler(new DataHandler(new ByteArrayDataSource(content, "application/octet-stream")));
    bp2.addHeader("Content-Transfer-Encoding", "base64");
    bp2.addHeader("Content-ID", "part2@apache.org");
    mp.addBodyPart(bp2);
    message.setContent(mp);
    // Compute the correct content type
    message.saveChanges();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mp.writeTo(baos);
    String contentType = message.getContentType();
    InputStream in = new ByteArrayInputStream(baos.toByteArray());
    Attachments attachments;
    if (useFile) {
        attachments = new Attachments(in, contentType, true, getAttachmentsDir(), "1024");
    } else {
        attachments = new Attachments(in, contentType);
    }
    DataHandler dh = attachments.getDataHandler("part2@apache.org");
    byte[] content2 = IOUtils.toByteArray(dh.getInputStream());
    assertTrue(Arrays.equals(content, content2));
}
Also used : Random(java.util.Random) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PipedInputStream(java.io.PipedInputStream) ExceptionInputStream(org.apache.axiom.testutils.io.ExceptionInputStream) InputStream(java.io.InputStream) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Aggregations

ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)76 DataHandler (javax.activation.DataHandler)58 InputStream (java.io.InputStream)33 IOException (java.io.IOException)25 MimeMultipart (javax.mail.internet.MimeMultipart)23 Test (org.junit.Test)19 DataSource (javax.activation.DataSource)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 ByteArrayInputStream (java.io.ByteArrayInputStream)14 ArrayList (java.util.ArrayList)14 MessagingException (javax.mail.MessagingException)14 MimeMessage (javax.mail.internet.MimeMessage)12 Holder (javax.xml.ws.Holder)7 List (java.util.List)6 AttachmentImpl (org.apache.cxf.attachment.AttachmentImpl)6 Attachment (org.apache.cxf.message.Attachment)6 Date (java.util.Date)5 HashMap (java.util.HashMap)5 ContentDisposition (com.zimbra.common.mime.ContentDisposition)4