List of usage examples for org.bouncycastle.mail.smime SMIMEEnveloped SMIMEEnveloped
public SMIMEEnveloped(MimeMessage message) throws MessagingException, CMSException
From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testEncrytedAS2Message() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); String mid = RANDOM.toString(); partnershipDVO.setIsOutboundEncryptRequired(true); AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); // Decrypt Message SMIMEEnveloped crypted = new SMIMEEnveloped(as2Msg.getBodyPart()); RecipientId recId = new RecipientId(); recId.setSerialNumber(partnershipDVO.getEncryptX509Certificate().getSerialNumber()); recId.setIssuer(partnershipDVO.getEncryptX509Certificate().getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = crypted.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); KeyStoreManager keyMan = (KeyStoreManager) TARGET.getSystemModule().getComponent("keystore-manager"); MimeBodyPart decrpted = SMIMEUtil.toMimeBodyPart(recipient.getContent(keyMan.getPrivateKey(), "BC")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOHandler.pipe(decrpted.getDataHandler().getInputStream(), baos); byte[] decrptedBA = baos.toByteArray(); byte[] originalBA = IOHandler.readBytes(FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG)); Assert.assertTrue(Arrays.equals(decrptedBA, originalBA)); //Assert the filename String filenameHdr = decrpted.getHeader("Content-Disposition")[0]; Assert.assertEquals("Filename value lost in BodyPartHeader", MOCK_AS2_MSG, getFileName(filenameHdr)); //Verify MIC/*w w w . j a va 2s . c o m*/ ByteArrayOutputStream contentStream = new ByteArrayOutputStream(); decrpted.writeTo(contentStream); byte[] content = (contentStream.toByteArray()); String mic = calculateMIC(content); Assert.assertEquals("MIC Value is not valid.", mic, getStoredMessage(mid).getMicValue()); }
From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testSignedEncryptedAS2Message() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); // Prepare Data String mid = RANDOM.toString(); partnershipDVO.setIsOutboundEncryptRequired(true); partnershipDVO.setIsOutboundSignRequired(true); //Encrypt message AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); // Decrypt Message SMIMEEnveloped crypted = new SMIMEEnveloped(as2Msg.getBodyPart()); RecipientId recId = new RecipientId(); recId.setSerialNumber(partnershipDVO.getEncryptX509Certificate().getSerialNumber()); recId.setIssuer(partnershipDVO.getEncryptX509Certificate().getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = crypted.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); KeyStoreManager keyMan = (KeyStoreManager) TARGET.getSystemModule().getComponent("keystore-manager"); MimeBodyPart decrpted = SMIMEUtil.toMimeBodyPart(recipient.getContent(keyMan.getPrivateKey(), "BC")); //Verify Signature try {//from ww w.ja v a 2s. co m SMIMESigned signed = new SMIMESigned((MimeMultipart) decrpted.getContent()); SignerInformationStore signers = signed.getSignerInfos(); Iterator signerInfos = signers.getSigners().iterator(); while (signerInfos.hasNext()) { SignerInformation signerInfo = (SignerInformation) signerInfos.next(); if (!signerInfo.verify(partnershipDVO.getEffectiveVerifyCertificate(), "BC")) { Assert.fail("Signature Verfifcation Failed"); } } //Assert the filename value MimeBodyPart signedPart = signed.getContent(); String filenameHdr = signedPart.getHeader("Content-Disposition")[0]; Assert.assertEquals("Lost Filename Header Information", MOCK_AS2_MSG, getFileName(filenameHdr)); // Verify MIC Value ByteArrayOutputStream baos = new ByteArrayOutputStream(); signedPart.writeTo(baos); byte[] content = (baos.toByteArray()); String mic = calculateMIC(content); MessageDVO msgDVO = getStoredMessage(mid); Assert.assertEquals("MIC Value is not valid.", mic, msgDVO.getMicValue()); } catch (Exception exp) { Assert.fail("Signature Verfifcation Failed"); } Assert.assertTrue(true); }
From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java
License:Open Source License
/** * Decrypts the encapsulated MIME body part. * /*from w w w. j av a 2s .c o m*/ * @param privateKey the private key for decryption. * @return an S/MIME message encapsulating the decrypted MIME body part. * @throws SMimeException if unable to decrpyt the body part. */ public SMimeMessage decrypt(PrivateKey privateKey) throws SMimeException { if (privateKey == null) { throw new SMimeException("Private key not found"); } try { setDefaults(); SMIMEEnveloped m = new SMIMEEnveloped(bodyPart); RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient == null) { throw new SMimeException("Invalid encrypted content"); } ByteArrayInputStream ins = new ByteArrayInputStream(recipient.getContent(privateKey, "BC")); MimeBodyPart decryptedPart = new MimeBodyPart(ins); return new SMimeMessage(decryptedPart, this); } catch (Exception e) { throw new SMimeException("Unable to decrypt body part", e); } }
From source file:io.aos.crypto.spl09.EnvelopedMailExample.java
License:Apache License
public static void main(String args[]) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); X509Certificate cert = (X509Certificate) chain[0]; // create the message we want encrypted MimeBodyPart dataPart = new MimeBodyPart(); dataPart.setText("Hello world!"); // set up the generator SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(cert);// w w w . ja va2s.c o m // generate the enveloped message MimeBodyPart envPart = gen.generate(dataPart, SMIMEEnvelopedGenerator.AES256_CBC, "BC"); // create the mail message MimeMessage mail = Utils.createMimeMessage("example enveloped message", envPart.getContent(), envPart.getContentType()); // create the enveloped object from the mail message SMIMEEnveloped enveloped = new SMIMEEnveloped(mail); // look for our recipient identifier RecipientId recId = new KEKRecipientId(null); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = enveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { // decryption step MimeBodyPart recoveredPart = SMIMEUtil.toMimeBodyPart(recipient.getContent(key, "BC")); // content display step System.out.print("Content: "); System.out.println(recoveredPart.getContent()); } else { System.out.println("could not find a matching recipient"); } }
From source file:io.aos.crypto.spl09.EnvelopedSignedMailExample.java
License:Apache License
public static void main(String[] args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); CertStore certsAndCRLs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain)), "BC"); X509Certificate cert = (X509Certificate) chain[0]; // create the message we want signed MimeBodyPart dataPart = new MimeBodyPart(); dataPart.setText("Hello world!"); // create the signed message MimeMultipart signedMultipart = SignedMailExample.createMultipartWithSignature(key, cert, certsAndCRLs, dataPart);// w ww . j a v a 2 s . c o m // create the body part containing the signed message MimeBodyPart signedPart = new MimeBodyPart(); signedPart.setContent(signedMultipart); // set up the enveloped message generator SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(cert); // generate the enveloped message MimeBodyPart envPart = gen.generate(signedPart, SMIMEEnvelopedGenerator.AES256_CBC, "BC"); // create the mail message MimeMessage mail = Utils.createMimeMessage("example signed and enveloped message", envPart.getContent(), envPart.getContentType()); // create the enveloped object from the mail message SMIMEEnveloped enveloped = new SMIMEEnveloped(mail); // look for our recipient identifier RecipientId recId = new KEKRecipientId(null); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = enveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); // decryption step MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(key, "BC")); // extract the multi-part from the body part. if (res.getContent() instanceof MimeMultipart) { SMIMESigned signed = new SMIMESigned((MimeMultipart) res.getContent()); // verification step X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS); if (isValid(signed, rootCert)) { System.out.println("verification succeeded"); } else { System.out.println("verification failed"); } // content display step MimeBodyPart content = signed.getContent(); System.out.print("Content: "); System.out.println(content.getContent()); } else { System.out.println("wrong content found"); } }
From source file:mitm.common.security.cms.CMSEnvelopedInspectorImplTest.java
License:Open Source License
@Test public void testEnveloped() throws MessagingException, CMSException, CryptoMessageSyntaxException, IOException { MimeMessage message = loadMessage("encrypted-validcertificate.eml"); SMIMEEnveloped enveloped = new SMIMEEnveloped(message); CMSEnvelopedDataAdapter cmsEnveloped = CMSAdapterFactory.createAdapter(enveloped); assertTrue(cmsEnveloped instanceof CMSEnvelopedDataAdapterImpl); testEnveloped(cmsEnveloped);/*from w w w .j av a2s.c o m*/ }
From source file:mitm.common.security.cms.CMSEnvelopedInspectorImplTest.java
License:Open Source License
@Test public void testEnvelopedMultipleRecipients() throws MessagingException, CMSException, CryptoMessageSyntaxException, IOException { MimeMessage message = loadMessage("encrypt-15-recipients.eml"); SMIMEEnveloped enveloped = new SMIMEEnveloped(message); CMSEnvelopedDataAdapter cmsEnveloped = CMSAdapterFactory.createAdapter(enveloped); assertTrue(cmsEnveloped instanceof CMSEnvelopedDataAdapterImpl); testEnvelopedMultipleRecipients(cmsEnveloped); }
From source file:mitm.common.security.cms.CMSEnvelopedInspectorImplTest.java
License:Open Source License
@Test(expected = RecipientInfoException.class) public void testDecryptIncorrectKey() throws Exception { MimeMessage message = loadMessage("encrypted-validcertificate.eml"); SMIMEEnveloped enveloped = new SMIMEEnveloped(message); CMSEnvelopedDataAdapter cmsEnveloped = CMSAdapterFactory.createAdapter(enveloped); assertTrue(cmsEnveloped instanceof CMSEnvelopedDataAdapterImpl); testDecryptIncorrectKey(cmsEnveloped); }
From source file:mitm.common.security.cms.CMSEnvelopedInspectorImplTest.java
License:Open Source License
@Test public void testDecryptMulitpleTimes() throws Exception { MimeMessage message = loadMessage("encrypted-validcertificate.eml"); SMIMEEnveloped enveloped = new SMIMEEnveloped(message); CMSEnvelopedDataAdapter cmsEnveloped = CMSAdapterFactory.createAdapter(enveloped); assertTrue(cmsEnveloped instanceof CMSEnvelopedDataAdapterImpl); testDecryptMulitpleTimes(cmsEnveloped); }
From source file:net.markenwerk.utils.mail.smime.SmimeUtil.java
License:Open Source License
/** * Decrypts a S/MIME encrypted MIME message and yields a new MIME message. * //from ww w .j a va 2s. co m * @param session * The {@link Session} that is used in conjunction with the * encrypted {@link MimeMessage}. * @param mimeMessage * The encrypted {@link MimeMessage} to be decrypted. * @param smimeKey * The {@link SmimeKey} used to obtain the {@link PrivateKey} to * decrypt the encrypted message with. * @return The new S/MIME decrypted {@link MimeMessage}. */ public static MimeMessage decrypt(Session session, MimeMessage mimeMessage, SmimeKey smimeKey) { try { byte[] content = decryptContent(new SMIMEEnveloped(mimeMessage), smimeKey); MimeBodyPart mimeBodyPart = SMIMEUtil.toMimeBodyPart(content); MimeMessage decryptedMessage = new MimeMessage(session); copyHeaderLines(mimeMessage, decryptedMessage); copyContent(mimeBodyPart, decryptedMessage); decryptedMessage.setHeader("Content-Type", mimeBodyPart.getContentType()); return decryptedMessage; } catch (Exception e) { throw handledException(e); } }