Example usage for org.bouncycastle.cms RecipientId match

List of usage examples for org.bouncycastle.cms RecipientId match

Introduction

In this page you can find the example usage for org.bouncycastle.cms RecipientId match.

Prototype

boolean match(T obj);

Source Link

Document

Match the passed in object, returning true if it would be selected by this selector, false otherwise.

Usage

From source file:org.apache.james.mailet.crypto.mailet.SMIMEDecrypt.java

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 *//*from w  w w  .  j  a va  2s  . co m*/
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            Collection<RecipientInformation> recipients = env.getRecipientInfos().getRecipients();
            for (Iterator<RecipientInformation> iter = recipients.iterator(); iter.hasNext();) {
                RecipientInformation info = (RecipientInformation) iter.next();
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        MimeBodyPart part = SMIMEUtil
                                .toMimeBodyPart(info.getContent(keyHolder.getPrivateKey(), "BC"));
                        // strippedMessage contains the decrypted message.
                        strippedMessage = part;
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.apache.james.transport.mailet.SMIMEDecrypt.java

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 *///from  ww w . j  a v  a2s .c o  m
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            @SuppressWarnings("unchecked")
            Collection<RecipientInformation> recipients = env.getRecipientInfos().getRecipients();
            Iterator<RecipientInformation> iter = recipients.iterator();
            while (iter.hasNext()) {
                RecipientInformation info = iter.next();
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        @SuppressWarnings("deprecation")
                        MimeBodyPart part = SMIMEUtil
                                .toMimeBodyPart(info.getContent(keyHolder.getPrivateKey(), "BC"));
                        // strippedMessage contains the decrypted message.
                        strippedMessage = part;
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.apache.james.transport.mailets.smime.SMIMEDecrypt.java

License:Apache License

public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;/* w w w  .  java2s  .c  om*/
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            Collection recipients = env.getRecipientInfos().getRecipients();
            for (Iterator iter = recipients.iterator(); iter.hasNext();) {
                RecipientInformation info = (RecipientInformation) iter.next();
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        MimeBodyPart part = SMIMEUtil
                                .toMimeBodyPart(info.getContent(keyHolder.getPrivateKey(), "BC"));
                        // strippedMessage contains the decrypted message.
                        strippedMessage = part;
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList list = new ArrayList(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.apache.james.transport.mailets.SMIMEDecrypt.java

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 *//*from  w w  w. j av  a 2  s.  c o  m*/
@SuppressWarnings("unchecked")
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            RecipientInformationStore informationStore = env.getRecipientInfos();
            Collection<RecipientInformation> recipients = informationStore.getRecipients();
            for (RecipientInformation info : recipients) {
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient(
                                keyHolder.getPrivateKey());
                        // strippedMessage contains the decrypted message.
                        strippedMessage = SMIMEUtil.toMimeBodyPart(info.getContent(recipient));
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.sejda.sambox.pdmodel.encryption.PublicKeySecurityHandler.java

License:Apache License

/**
 * Prepares everything to decrypt the document.
 *
 * @param encryption encryption dictionary, can be retrieved via
 * {@link PDDocument#getEncryption()}/*from   w  w  w.j a v  a2s  .  com*/
 * @param documentIDArray document id which is returned via
 * {@link org.apache.pdfbox.cos.COSDocument#getDocumentID()} (not used by
 * this handler)
 * @param decryptionMaterial Information used to decrypt the document.
 *
 * @throws IOException If there is an error accessing data. If verbose mode
 * is enabled, the exception message will provide more details why the
 * match wasn't successful.
 */
@Override
public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray,
        DecryptionMaterial decryptionMaterial) throws IOException {
    if (!(decryptionMaterial instanceof PublicKeyDecryptionMaterial)) {
        throw new IOException("Provided decryption material is not compatible with the document");
    }

    setDecryptMetadata(encryption.isEncryptMetaData());
    if (encryption.getLength() != 0) {
        this.keyLength = encryption.getLength();
    }

    PublicKeyDecryptionMaterial material = (PublicKeyDecryptionMaterial) decryptionMaterial;

    try {
        boolean foundRecipient = false;

        // the decrypted content of the enveloped data that match
        // the certificate in the decryption material provided
        byte[] envelopedData = null;

        // the bytes of each recipient in the recipients array
        byte[][] recipientFieldsBytes = new byte[encryption.getRecipientsLength()][];

        int recipientFieldsLength = 0;
        int i = 0;
        StringBuilder extraInfo = new StringBuilder();
        for (; i < encryption.getRecipientsLength(); i++) {
            COSString recipientFieldString = encryption.getRecipientStringAt(i);
            byte[] recipientBytes = recipientFieldString.getBytes();
            CMSEnvelopedData data = new CMSEnvelopedData(recipientBytes);
            Iterator<?> recipCertificatesIt = data.getRecipientInfos().getRecipients().iterator();
            int j = 0;
            while (recipCertificatesIt.hasNext()) {
                RecipientInformation ri = (RecipientInformation) recipCertificatesIt.next();
                // Impl: if a matching certificate was previously found it is an error,
                // here we just don't care about it
                X509Certificate certificate = material.getCertificate();
                X509CertificateHolder materialCert = null;
                if (null != certificate) {
                    materialCert = new X509CertificateHolder(certificate.getEncoded());
                }
                RecipientId rid = ri.getRID();
                if (rid.match(materialCert) && !foundRecipient) {
                    foundRecipient = true;
                    PrivateKey privateKey = (PrivateKey) material.getPrivateKey();
                    envelopedData = ri
                            .getContent(new JceKeyTransEnvelopedRecipient(privateKey).setProvider("BC"));
                    break;
                }
                j++;
                if (certificate != null) {
                    extraInfo.append('\n');
                    extraInfo.append(j);
                    extraInfo.append(": ");
                    if (rid instanceof KeyTransRecipientId) {
                        appendCertInfo(extraInfo, (KeyTransRecipientId) rid, certificate, materialCert);
                    }
                }
            }
            recipientFieldsBytes[i] = recipientBytes;
            recipientFieldsLength += recipientBytes.length;
        }
        if (!foundRecipient || envelopedData == null) {
            throw new IOException(
                    "The certificate matches none of " + i + " recipient entries" + extraInfo.toString());
        }
        if (envelopedData.length != 24) {
            throw new IOException("The enveloped data does not contain 24 bytes");
        }
        // now envelopedData contains:
        // - the 20 bytes seed
        // - the 4 bytes of permission for the current user

        byte[] accessBytes = new byte[4];
        System.arraycopy(envelopedData, 20, accessBytes, 0, 4);

        AccessPermission currentAccessPermission = new AccessPermission(accessBytes);
        currentAccessPermission.setReadOnly();
        setCurrentAccessPermission(currentAccessPermission);

        // what we will put in the SHA1 = the seed + each byte contained in the recipients array
        byte[] sha1Input = new byte[recipientFieldsLength + 20];

        // put the seed in the sha1 input
        System.arraycopy(envelopedData, 0, sha1Input, 0, 20);

        // put each bytes of the recipients array in the sha1 input
        int sha1InputOffset = 20;
        for (byte[] recipientFieldsByte : recipientFieldsBytes) {
            System.arraycopy(recipientFieldsByte, 0, sha1Input, sha1InputOffset, recipientFieldsByte.length);
            sha1InputOffset += recipientFieldsByte.length;
        }

        MessageDigest md = MessageDigests.getSHA1();
        byte[] mdResult = md.digest(sha1Input);

        // we have the encryption key ...
        encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, encryptionKey, 0, this.keyLength / 8);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (KeyStoreException e) {
        throw new IOException(e);
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    }
}