Example usage for org.bouncycastle.mail.smime SMIMEEnveloped getRecipientInfos

List of usage examples for org.bouncycastle.mail.smime SMIMEEnveloped getRecipientInfos

Introduction

In this page you can find the example usage for org.bouncycastle.mail.smime SMIMEEnveloped getRecipientInfos.

Prototype

public RecipientInformationStore getRecipientInfos() 

Source Link

Document

return a store of the intended recipients for this message

Usage

From source file:org.openhealthtools.openatna.net.MailConnection.java

License:Apache License

public MimeBodyPart decryptMessage(Message message) throws MessagingException {

    try {// www . jav a  2 s.  c o  m
        /* Add BC */
        Security.addProvider(new BouncyCastleProvider());
        // Open the key store
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray());

        // find the certificate for the private key and generate a
        // suitable recipient identifier.
        X509Certificate cert = (X509Certificate) ks.getCertificate(getSenderKeyAlias());
        RecipientId recId = new RecipientId();

        recId.setSerialNumber(cert.getSerialNumber());
        recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

        SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);
        RecipientInformationStore recipients = m.getRecipientInfos();
        // TODO figure out why this doesn't work...
        //RecipientInformation        recipient = recipients.get(recId);
        RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next();

        Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray());
        byte[] byteContent = recipient.getContent(key, "BC");
        MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent);
        return res;

    } catch (Exception e) {
        log.error("Problem decrypting message: ", e);
        throw new MessagingException(e.getMessage());
    }
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

/**
 * Method to decrypt files attached to SMIME (not signed) messages
 *///from   w w w .  ja  va2  s. c om
public byte[] decryptMessage(byte[] encryptedFile) throws Exception {
    MimeMessage msg = new MimeMessage(ContextVS.MAIL_SESSION, new ByteArrayInputStream(encryptedFile));
    SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(msg);
    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipientInfo = recipients.get(recipientId);
    RecipientId messageRecipientId = null;
    if (recipientInfo != null && recipientInfo.getRID() != null) {
        messageRecipientId = recipientInfo.getRID();
        log.info("messageRecipientId.getSerialNumber(): " + messageRecipientId.getSerialNumber());
    } else
        throw new ExceptionVS("No message found for recipientId: " + recipientId.getSerialNumber());
    MimeBodyPart mimeMessage = SMIMEUtil.toMimeBodyPart(recipientInfo.getContent(recipient));
    /*ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mimeMessage.writeTo(baos)
    log.info(" mimeMessage: ${new String(baos.toByteArray())}")*/
    Object messageContent = mimeMessage.getContent();
    byte[] messageContentBytes = null;
    //log.info(" messageContent class: ${messageContent?.getClass()}")
    if (messageContent instanceof MimeMultipart) {
        MimeMultipart mimeMultipart = (MimeMultipart) messageContent;
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        InputStream stream = bodyPart.getInputStream();
        ByteArrayOutputStream bodyPartOutputStream = new ByteArrayOutputStream();
        byte[] buf = new byte[2048];
        int len;
        while ((len = stream.read(buf)) > 0) {
            bodyPartOutputStream.write(buf, 0, len);
        }
        stream.close();
        bodyPartOutputStream.close();
        messageContentBytes = bodyPartOutputStream.toByteArray();
    } else if (messageContent instanceof byte[]) {
        messageContentBytes = (byte[]) messageContent;
    } else if (messageContent instanceof String) {
        //log.info(" messageContent: ${messageContent}")
        String[] votingHeaders = mimeMessage.getHeader("votingSystemMessageType");
        String encodedContentType = null;
        if (votingHeaders != null && votingHeaders.length > 0)
            encodedContentType = mimeMessage.getHeader("votingSystemMessageType")[0];
        if (encodedContentType != null) {
            if (ContextVS.BASE64_ENCODED_CONTENT_TYPE.equals(encodedContentType)) {
                messageContentBytes = Base64.getDecoder().decode((String) messageContent);
            } else
                log.log(Level.SEVERE, "### unknown  votingSystemMessageType: " + encodedContentType);
        } else
            messageContentBytes = messageContent.toString().getBytes();
    }
    return messageContentBytes;
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

/**
 * Method to decrypt SMIME signed messages
 *///  www . j a v a2  s  . c  om
public ResponseVS decryptSMIME(byte[] encryptedMessageBytes) throws Exception {
    SMIMEMessage smimeMessageReq = null;
    MimeMessage msg = new MimeMessage(ContextVS.MAIL_SESSION, new ByteArrayInputStream(encryptedMessageBytes));
    //String encryptedMessageBytesStr = new String(encryptedMessageBytes);
    //log.info("- decryptSMIME - encryptedMessageBytesStr: " + encryptedMessageBytesStr)
    SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(msg);
    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipientInfo = recipients.get(recipientId);
    /*RecipientId recipientRID = null;
    if(recipient.getRID() != null) {
    recipientRID = recipient.getRID();
    log.info(" -- recipientRID.getSerialNumber(): " + recipientRID.getSerialNumber());
    if(recipient.getRID().getCertificate() != null) {
       log.info(" -- recipient: " + recipient.getRID().getCertificate().getSubjectDN().toString());
    } else log.info(" -- recipient.getRID().getCertificate() NULL");
    } else log.info(" -- getRID NULL");
    MimeBodyPart res = SMIMEUtil.toMimeBodyPart(
     recipient.getContent(new JceKeyTransEnvelopedRecipient(serverPrivateKey).setProvider("BC")));*/
    if (recipientInfo == null) {
        log.log(Level.SEVERE, "Expected recipientId.getSerialNumber(): " + recipientId.getSerialNumber());
        Collection<RecipientInformation> recipientCollection = recipients.getRecipients();
        for (RecipientInformation recipientInf : recipientCollection) {
            log.log(Level.SEVERE, "Encrypted document recipientId.getSerialNumber(): "
                    + recipientInf.getRID().getSerialNumber());
        }
        return new ResponseVS(ResponseVS.SC_ERROR_REQUEST, ContextVS.getMessage("encryptionRecipientErrorMsg"));
    }
    byte[] messageContentBytes = recipientInfo.getContent(recipient);
    //log.info(" ------- Message Contents: ${new String(messageContentBytes)}");
    smimeMessageReq = new SMIMEMessage(new ByteArrayInputStream(messageContentBytes));
    ResponseVS responseVS = new ResponseVS(ResponseVS.SC_OK);
    responseVS.setSMIME(smimeMessageReq);
    return responseVS;
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

/**
 * helper method to decrypt SMIME signed messages
 *//*from   w ww .j  av a  2 s .c  o  m*/
public static byte[] decryptMessage(byte[] encryptedMessageBytes, PrivateKey receiverPrivateKey)
        throws Exception {
    log.info("decryptMessage(...) ");
    RecipientId recId = null;
    /*if(receiverCert != null) recId = new JceKeyTransRecipientId(receiverCert);*/
    Recipient recipient = new JceKeyTransEnvelopedRecipient(receiverPrivateKey).setProvider(ContextVS.PROVIDER);
    MimeMessage msg = new MimeMessage(null, new ByteArrayInputStream(encryptedMessageBytes));
    SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(msg);
    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipientInfo = null;
    //if(recId != null) recipientInfo = recipients.get(recId);
    if (recipientInfo == null && recipients.getRecipients().size() == 1) {
        recipientInfo = (RecipientInformation) recipients.getRecipients().iterator().next();
    }
    byte[] messageBytes = recipientInfo.getContent(recipient);
    return messageBytes;
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

public static byte[] decryptFile(byte[] encryptedFile, PublicKey publicKey, PrivateKey receiverPrivateKey)
        throws Exception {
    RecipientId recId = new KeyTransRecipientId(publicKey.getEncoded());
    Recipient recipient = new JceKeyTransEnvelopedRecipient(receiverPrivateKey).setProvider(ContextVS.PROVIDER);
    MimeMessage msg = new MimeMessage(null, new ByteArrayInputStream(encryptedFile));
    SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(msg);
    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipientInfo = null;
    recipientInfo = recipients.get(recId);
    if (recipientInfo == null && recipients.getRecipients().size() == 1) {
        recipientInfo = (RecipientInformation) recipients.getRecipients().iterator().next();
    }//from   ww w. j  av a  2s  .  co  m
    RecipientId fileRecipientId = null;
    if (recipientInfo.getRID() != null) {
        fileRecipientId = recipientInfo.getRID();
    }
    byte[] result = recipientInfo.getContent(recipient);
    return result;
}