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++;
}
}
}
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);
}
}
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");
}
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);
}
}
}
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());
}
Aggregations