Search in sources :

Example 1 with RecipientInformationStore

use of org.bouncycastle.cms.RecipientInformationStore in project nhin-d by DirectProject.

the class SMIMECryptographerImpl method decrypt.

/**
     * Decrypts an entity with the provided certificates' private key.
     * @param encryptedEntity The entity that will be decrypted.
     * @param decryptingCertificate The certificates whose private keys will be used to decrypt the message.
     * @return A MimeEntity containing the decrypted part.
     */
public MimeEntity decrypt(MimeEntity encryptedEntity, Collection<X509CertificateEx> decryptingCertificates) {
    if (decryptingCertificates == null || decryptingCertificates.size() == 0) {
        throw new IllegalArgumentException();
    }
    MimeEntity retEntity = null;
    try {
        if (LOGGER.isDebugEnabled()) {
            final byte[] encryptedContent = encryptedEntity.getContentAsBytes();
            writePreDecrypt(encryptedContent);
        }
        final SMIMEEnveloped m = new SMIMEEnveloped(encryptedEntity);
        if (!this.isAllowedEncryptionAlgorithm(m.getEncryptionAlgOID()))
            throw new NHINDException(MimeError.DisallowedEncryptionAlgorithm, "The encryption algorithm " + m.getEncryptionAlgOID() + " is not allowed");
        for (X509CertificateEx decryptCert : decryptingCertificates) {
            final RecipientId recId = generateRecipientSelector(decryptCert);
            final RecipientInformationStore recipients = m.getRecipientInfos();
            final DirectRecipientInformation recipient = decFactory.createInstance(recipients.get(recId), m);
            if (recipient == null)
                continue;
            final byte[] decryptedPayload = recipient.getDecryptedContent(decryptCert.getPrivateKey());
            if (LOGGER.isDebugEnabled()) {
                writePostDecrypt(decryptedPayload);
            }
            final ByteArrayInputStream inStream = new ByteArrayInputStream(decryptedPayload);
            retEntity = new MimeEntity(inStream);
            break;
        }
    } catch (MessagingException e) {
        throw new MimeException(MimeError.InvalidMimeEntity, e);
    } catch (Exception e) {
        throw new MimeException(MimeError.Unexpected, e);
    }
    if (retEntity == null) {
        throw new NHINDException(MimeError.Unexpected, "None of the the provided decryption certs were found in message's RecipientsInfo set.");
    }
    return retEntity;
}
Also used : RecipientId(org.bouncycastle.cms.RecipientId) MessagingException(javax.mail.MessagingException) DirectRecipientInformation(org.nhindirect.stagent.cryptography.activekeyops.DirectRecipientInformation) SMIMEEnveloped(org.bouncycastle.mail.smime.SMIMEEnveloped) NHINDException(org.nhindirect.stagent.NHINDException) MessagingException(javax.mail.MessagingException) MimeException(org.nhindirect.stagent.mail.MimeException) NHINDException(org.nhindirect.stagent.NHINDException) ParseException(javax.mail.internet.ParseException) IOException(java.io.IOException) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) RecipientInformationStore(org.bouncycastle.cms.RecipientInformationStore) MimeException(org.nhindirect.stagent.mail.MimeException)

Example 2 with RecipientInformationStore

use of org.bouncycastle.cms.RecipientInformationStore in project ats-framework by Axway.

the class SMimePackageEncryptor method decrypt.

@PublicAtsApi
public Package decrypt(Package sourcePackage) throws ActionException {
    // for connection management to IMAP store
    boolean storeReconnected = false;
    if (sourcePackage instanceof MimePackage) {
        try {
            storeReconnected = ((MimePackage) sourcePackage).reconnectStoreIfClosed();
        } catch (MessagingException ex) {
            throw new ActionException("Could not reopen IMAP connection", ex);
        }
    }
    try {
        KeyStore ks = getKeystore();
        RecipientId recId = new JceKeyTransRecipientId((X509Certificate) ks.getCertificate(aliasOrCN));
        MimeMessage msg = getMimeMessage(sourcePackage);
        SMIMEEnveloped m = new SMIMEEnveloped(msg);
        RecipientInformationStore recipients = m.getRecipientInfos();
        RecipientInformation recipient = recipients.get(recId);
        PrivateKey privateKey = (PrivateKey) ks.getKey(aliasOrCN, certPassword.toCharArray());
        JceKeyTransRecipient jceKey = new JceKeyTransEnvelopedRecipient(privateKey).setProvider(BouncyCastleProvider.PROVIDER_NAME);
        MimeBodyPart result = null;
        try {
            result = SMIMEUtil.toMimeBodyPart(recipient.getContent(jceKey));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Successfully decrypted message with subject '" + msg.getSubject() + "' with private key alias: " + aliasOrCN);
            }
        } catch (SMIMEException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not decrypt message with subject '" + sourcePackage.getSubject() + "' with private key alias '" + aliasOrCN + "'", e);
            }
        }
        SMIMESigned signedMessage = null;
        MimeMessage decryptedMsg = new MimeMessage(Session.getInstance(new Properties()));
        if (result != null) {
            Object content = result.getContent();
            Enumeration<?> hLineEnum = msg.getAllHeaderLines();
            while (hLineEnum.hasMoreElements()) {
                decryptedMsg.addHeaderLine((String) hLineEnum.nextElement());
            }
            decryptedMsg.setContent(content, result.getContentType());
            // in order getPlainTextBody getHtmlTextBody to work as they do not work with attachments
            decryptedMsg.removeHeader("Content-Disposition");
            // check if the message is signed
            try {
                if (content instanceof MimeMultipart) {
                    MimeMultipart multipartContent = (MimeMultipart) content;
                    if (multipartContent.getContentType() != null && multipartContent.getContentType().toLowerCase().contains(CONTENT_TYPE_MULTIPART_SIGNED)) {
                        signedMessage = new SMIMESigned(multipartContent);
                    }
                } else if (content instanceof SMIMESigned) {
                    signedMessage = (SMIMESigned) content;
                } else if (content instanceof BASE64DecoderStream) {
                    // com.sun.mail.util.BASE64DecoderStream - JavaMail API dependency. Seems still available
                    // in JavaMail 2.0 so not an issue if using other non-Oracle/OpenJDK JVMs
                    // will throw exception if not signed
                    signedMessage = new SMIMESigned(decryptedMsg);
                }
            } catch (Exception e) {
            // the message is not signed
            // log.debug( "Could not construct signed message instance", e );
            }
        }
        if (signedMessage != null) {
            // remove signature from the message
            decryptedMsg.setContent(signedMessage.getContent().getContent(), signedMessage.getContent().getContentType());
            MimePackage mimePackage = new MimePackage(decryptedMsg);
            // keep the SMIMESigned message for further signature verification
            mimePackage.setSMIMESignedMessage(signedMessage);
            return mimePackage;
        }
        return new MimePackage(decryptedMsg);
    } catch (Exception e) {
        throw new ActionException(DECRYPTION_EXCEPTION, e);
    } finally {
        if (storeReconnected) {
            // and sourcePackage should be instanceof MimePackage
            try {
                ((MimePackage) sourcePackage).closeStoreConnection(true);
            } catch (MessagingException ex) {
                // do not hide possible exception thrown in catch block
                LOG.debug(ex);
            }
        }
    }
}
Also used : JceKeyTransRecipient(org.bouncycastle.cms.jcajce.JceKeyTransRecipient) SMIMESigned(org.bouncycastle.mail.smime.SMIMESigned) JceKeyTransRecipientId(org.bouncycastle.cms.jcajce.JceKeyTransRecipientId) RecipientId(org.bouncycastle.cms.RecipientId) PrivateKey(java.security.PrivateKey) MessagingException(javax.mail.MessagingException) BASE64DecoderStream(com.sun.mail.util.BASE64DecoderStream) JceKeyTransRecipientId(org.bouncycastle.cms.jcajce.JceKeyTransRecipientId) ActionException(com.axway.ats.action.model.ActionException) JceKeyTransEnvelopedRecipient(org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient) Properties(java.util.Properties) KeyStore(java.security.KeyStore) SMIMEEnveloped(org.bouncycastle.mail.smime.SMIMEEnveloped) MessagingException(javax.mail.MessagingException) ActionException(com.axway.ats.action.model.ActionException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) MimePackage(com.axway.ats.action.objects.MimePackage) RecipientInformation(org.bouncycastle.cms.RecipientInformation) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) RecipientInformationStore(org.bouncycastle.cms.RecipientInformationStore) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) MimeBodyPart(javax.mail.internet.MimeBodyPart) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 3 with RecipientInformationStore

use of org.bouncycastle.cms.RecipientInformationStore in project nhin-d by DirectProject.

the class MessagaeDecryptor method main.

public static void main(String[] args) {
    try {
        final KeyStore store = KeyStore.getInstance("pkcs12");
        store.load(FileUtils.openInputStream(new File("/users/gm2552/Desktop/ops.p12")), "".toCharArray());
        final String alias = store.aliases().nextElement();
        final PrivateKey entry = (PrivateKey) store.getKey(alias, "".toCharArray());
        final X509Certificate cert = (X509Certificate) store.getCertificate(alias);
        /*
			for (String arg :args)
			{
				if (arg )
			}
			*/
        //String encryptedStuff = FileUtils.readFileToString(new File("users/gm2552/Desktop/cry.eml"));
        InputStream inStream = FileUtils.openInputStream(new File("/users/gm2552/Desktop/cry2.eml"));
        MimeBodyPart part = new MimeBodyPart(inStream);
        final SMIMEEnveloped m = new SMIMEEnveloped(part);
        RecipientId recId = new RecipientId();
        recId.setIssuer(cert.getIssuerX500Principal().getEncoded());
        recId.setSerialNumber(cert.getSerialNumber());
        final RecipientInformationStore recipients = m.getRecipientInfos();
        final DirectRecipientInformation recipient = new SplitDirectRecipientInformationFactory().createInstance(recipients.get(recId), m);
        final byte[] decryptedPayload = recipient.getDecryptedContent(entry);
        System.out.println("Alg OID: " + m.getEncryptionAlgOID());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : PrivateKey(java.security.PrivateKey) RecipientId(org.bouncycastle.cms.RecipientId) InputStream(java.io.InputStream) DirectRecipientInformation(org.nhindirect.stagent.cryptography.activekeyops.DirectRecipientInformation) KeyStore(java.security.KeyStore) SMIMEEnveloped(org.bouncycastle.mail.smime.SMIMEEnveloped) X509Certificate(java.security.cert.X509Certificate) SplitDirectRecipientInformationFactory(org.nhindirect.stagent.cryptography.activekeyops.SplitDirectRecipientInformationFactory) RecipientInformationStore(org.bouncycastle.cms.RecipientInformationStore) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 4 with RecipientInformationStore

use of org.bouncycastle.cms.RecipientInformationStore in project xipki by xipki.

the class EnvelopedDataDecryptor method decrypt.

public byte[] decrypt(CMSEnvelopedData envData) throws MessageDecodingException {
    ScepUtil.requireNonNull("envData", envData);
    final RecipientInformationStore recipientInfos = envData.getRecipientInfos();
    RecipientInformation recipientInfo = null;
    EnvelopedDataDecryptorInstance decryptor = null;
    for (EnvelopedDataDecryptorInstance m : decryptors) {
        recipientInfo = recipientInfos.get(m.getRecipientId());
        if (recipientInfo != null) {
            decryptor = m;
            break;
        }
    }
    if (recipientInfo == null || decryptor == null) {
        throw new MessageDecodingException("missing expected key transfer recipient");
    }
    try {
        return recipientInfo.getContent(decryptor.getRecipient());
    } catch (CMSException ex) {
        throw new MessageDecodingException("could not decrypt the envelopedData");
    }
}
Also used : RecipientInformation(org.bouncycastle.cms.RecipientInformation) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) RecipientInformationStore(org.bouncycastle.cms.RecipientInformationStore) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

RecipientInformationStore (org.bouncycastle.cms.RecipientInformationStore)4 RecipientId (org.bouncycastle.cms.RecipientId)3 SMIMEEnveloped (org.bouncycastle.mail.smime.SMIMEEnveloped)3 KeyStore (java.security.KeyStore)2 PrivateKey (java.security.PrivateKey)2 MessagingException (javax.mail.MessagingException)2 MimeBodyPart (javax.mail.internet.MimeBodyPart)2 RecipientInformation (org.bouncycastle.cms.RecipientInformation)2 DirectRecipientInformation (org.nhindirect.stagent.cryptography.activekeyops.DirectRecipientInformation)2 ActionException (com.axway.ats.action.model.ActionException)1 MimePackage (com.axway.ats.action.objects.MimePackage)1 PublicAtsApi (com.axway.ats.common.PublicAtsApi)1 BASE64DecoderStream (com.sun.mail.util.BASE64DecoderStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 X509Certificate (java.security.cert.X509Certificate)1 Properties (java.util.Properties)1 MimeMessage (javax.mail.internet.MimeMessage)1