Example usage for org.bouncycastle.cms RecipientInformation getRID

List of usage examples for org.bouncycastle.cms RecipientInformation getRID

Introduction

In this page you can find the example usage for org.bouncycastle.cms RecipientInformation getRID.

Prototype

public RecipientId getRID() 

Source Link

Usage

From source file:be.e_contract.mycarenet.etee.Unsealer.java

License:Open Source License

@SuppressWarnings("unchecked")
private byte[] decrypt(byte[] encryptedData) throws CMSException, IOException {
    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(encryptedData);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    RecipientId recipientId = new JceKeyTransRecipientId(this.decryptionCertificate);
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients(recipientId);
    LOG.debug("number of recipients for given decryption cert: " + recipients.size());
    if (0 == recipients.size()) {
        recipients = recipientInformationStore.getRecipients();
        LOG.debug("number of all recipients: " + recipients.size());
        Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
        while (recipientsIterator.hasNext()) {
            RecipientInformation recipientInformation = recipientsIterator.next();
            RecipientId actualRecipientId = recipientInformation.getRID();
            LOG.debug("actual recipient id type: " + actualRecipientId.getClass().getName());
            if (actualRecipientId instanceof KeyTransRecipientId) {
                KeyTransRecipientId actualKeyTransRecipientId = (KeyTransRecipientId) actualRecipientId;
                LOG.debug("actual recipient issuer: " + actualKeyTransRecipientId.getIssuer());
                LOG.debug("actual recipient serial number: " + actualKeyTransRecipientId.getSerialNumber());
            }//ww  w  . j  a va 2  s .co m
        }
        throw new SecurityException("message does not seem to be addressed to you");
    }
    Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
    RecipientInformation recipientInformation = recipientsIterator.next();

    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(this.decryptionPrivateKey.getEncoded());
    BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams);
    byte[] decryptedContent = recipientInformation.getContent(recipient);
    return decryptedContent;
}

From source file:chapter9.KeyTransEnvelopedDataExample2.java

/**
 *
 * @param args/*from   w  w  w.j  av a2  s . c  o m*/
 * @throws Exception
 */
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];

    //1.- Set up the generator
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

    gen.addKeyTransRecipient(cert);

    //2.- Create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes());
    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC,
            CryptoDefs.Provider.BC.getName());

    //3.- Re-create
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    //4.- Look for our recipient identifier
    //    Set up to iterate through the recipients
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    CertStore certStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Collections.singleton(cert)), CryptoDefs.Provider.BC.getName());

    RecipientInformation recipient = null;
    for (Object o : recipients.getRecipients()) {
        recipient = (RecipientInformation) o;

        if (recipient instanceof KeyTransRecipientInformation) {
            //5.- Match the recipient ID
            Collection<?> matches = certStore.getCertificates(recipient.getRID());

            if (matches.isEmpty() == false) {
                //6.- Decrypt the data
                byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

                //7.- Compare recovered data to the original data
                if (Arrays.equals((byte[]) data.getContent(), recData) == true) {
                    System.out.println("\t data recovery succeeded!!");
                    break;
                } else {
                    System.out.println("\t data recovery failed!!");
                    break;
                }
            }
        }
    }

    if (recipient == null) {
        System.out.println("\t Could not find a matching recipient!!");
    }
}

From source file:com.cordys.coe.ac.emailio.util.smime.SMIMEUtil.java

License:Apache License

/**
 * This method will decrypt the source message and return the decrypted version of the mail.
 *
 * @param   mmSource  The message to decrypt.
 * @param   scConfig  The S/MIME configuration details.
 *
 * @return  The decrypted message./*from ww  w  .ja  va  2 s  .  c  om*/
 *
 * @throws  EmailIOException  In case of any exceptions.
 */
public static MimeMessage decryptMessage(MimeMessage mmSource, ISMIMEConfiguration scConfig)
        throws EmailIOException {
    MimeMessage mmReturn = null;

    // First we create the wrapper around the encrypted message
    try {
        SMIMEEnveloped seSMIME = new SMIMEEnveloped(mmSource);

        // Now get all recipients for this mail and try to find the matching certificate with
        // the private key.
        RecipientInformationStore recipients = seSMIME.getRecipientInfos();

        ICertificateInfo ciInfo = null;
        RecipientInformation riInfo = null;

        Collection<?> cRecipients = recipients.getRecipients();

        for (Iterator<?> iRecipients = cRecipients.iterator(); iRecipients.hasNext();) {
            riInfo = (RecipientInformation) iRecipients.next();

            // Figure out if we have a key for this recipient ID.
            ciInfo = scConfig.getCertificateInfo(riInfo.getRID());

            if (ciInfo != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found certificate info for RID " + riInfo.getRID());
                }

                break;
            }
        }

        // Check if we found all information.
        if (ciInfo == null) {
            throw new EmailIOException(
                    EmailIOExceptionMessages.EIOE_COULD_NOT_FIND_ANY_CERTIFICATE_INFORMATION_FOR_ANY_OF_THE_RECIPIENTS);
        }

        if (riInfo == null) {
            throw new EmailIOException(
                    EmailIOExceptionMessages.EIOE_COULD_NOT_DECRYPT_MESSAGE_BECAUSE_NO_RECIPIENT_INFORMATION_WAS_FOUND);
        }

        // We have all the necessary information, so now we can really decrypt the message.
        Key kPrivate = ciInfo.getKey();

        if (kPrivate == null) {
            throw new EmailIOException(
                    EmailIOExceptionMessages.EIOE_COULD_NOT_FIND_A_PRIVATE_KEY_FOR_RECIPIENT_0,
                    riInfo.getRID().getSubjectAsString());
        }

        // Do the actual decrypting of the content.
        MimeBodyPart res = org.bouncycastle.mail.smime.SMIMEUtil
                .toMimeBodyPart(riInfo.getContent(kPrivate, "BC"));

        // Now create a decrypted version of the mail.
        mmReturn = new MimeMessage(mmSource);

        MimeMultipart mmTemp = new MimeMultipart();
        mmTemp.addBodyPart(res);

        mmReturn.setContent(mmTemp);
        mmReturn.saveChanges();

        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "The message was now decrypted. Returning mail:\n" + MailMessageUtil.rawMessage(mmReturn));
        }
    } catch (EmailIOException eioe) {
        throw eioe;
    } catch (Exception e) {
        throw new EmailIOException(e, EmailIOExceptionMessages.EIOE_ERROR_DECRYPTING_EMAIL_MESSAGE);
    }

    return mmReturn;
}

From source file:com.itextpdf.kernel.crypto.securityhandler.EncryptionUtils.java

License:Open Source License

static byte[] fetchEnvelopedData(Key certificateKey, Certificate certificate, String certificateKeyProvider,
        IExternalDecryptionProcess externalDecryptionProcess, PdfArray recipients) {
    boolean foundRecipient = false;
    byte[] envelopedData = null;

    X509CertificateHolder certHolder;//from w w w.  jav  a 2s  .  com
    try {
        certHolder = new X509CertificateHolder(certificate.getEncoded());
    } catch (Exception f) {
        throw new PdfException(PdfException.PdfDecryption, f);
    }
    if (externalDecryptionProcess == null) {
        for (int i = 0; i < recipients.size(); i++) {
            PdfString recipient = recipients.getAsString(i);
            CMSEnvelopedData data;
            try {
                data = new CMSEnvelopedData(recipient.getValueBytes());
                Iterator<RecipientInformation> recipientCertificatesIt = data.getRecipientInfos()
                        .getRecipients().iterator();
                while (recipientCertificatesIt.hasNext()) {
                    RecipientInformation recipientInfo = recipientCertificatesIt.next();

                    if (recipientInfo.getRID().match(certHolder) && !foundRecipient) {
                        envelopedData = PdfEncryptor.getContent(recipientInfo, (PrivateKey) certificateKey,
                                certificateKeyProvider);
                        foundRecipient = true;
                    }
                }
            } catch (Exception f) {
                throw new PdfException(PdfException.PdfDecryption, f);
            }
        }
    } else {
        for (int i = 0; i < recipients.size(); i++) {
            PdfString recipient = recipients.getAsString(i);
            CMSEnvelopedData data;
            try {
                data = new CMSEnvelopedData(recipient.getValueBytes());
                RecipientInformation recipientInfo = data.getRecipientInfos()
                        .get(externalDecryptionProcess.getCmsRecipientId());
                if (recipientInfo != null) {
                    envelopedData = recipientInfo.getContent(externalDecryptionProcess.getCmsRecipient());
                    foundRecipient = true;
                }
            } catch (Exception f) {
                throw new PdfException(PdfException.PdfDecryption, f);
            }
        }
    }

    if (!foundRecipient || envelopedData == null) {
        throw new PdfException(PdfException.BadCertificateAndKey);
    }
    return envelopedData;
}

From source file:com.itextpdf.text.pdf.PdfReader.java

License:Open Source License

/**
 * @throws IOException//from ww w  .  j a v  a 2  s . c o m
 */
@SuppressWarnings("unchecked")
private void readDecryptedDocObj() throws IOException {
    if (encrypted)
        return;
    PdfObject encDic = trailer.get(PdfName.ENCRYPT);
    if (encDic == null || encDic.toString().equals("null"))
        return;
    encryptionError = true;
    byte[] encryptionKey = null;
    encrypted = true;
    PdfDictionary enc = (PdfDictionary) getPdfObject(encDic);

    String s;
    PdfObject o;

    PdfArray documentIDs = trailer.getAsArray(PdfName.ID);
    byte documentID[] = null;
    if (documentIDs != null) {
        o = documentIDs.getPdfObject(0);
        strings.remove(o);
        s = o.toString();
        documentID = com.itextpdf.text.DocWriter.getISOBytes(s);
        if (documentIDs.size() > 1)
            strings.remove(documentIDs.getPdfObject(1));
    }
    // just in case we have a broken producer
    if (documentID == null)
        documentID = new byte[0];
    byte uValue[] = null;
    byte oValue[] = null;
    int cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
    int lengthValue = 0;

    PdfObject filter = getPdfObjectRelease(enc.get(PdfName.FILTER));

    if (filter.equals(PdfName.STANDARD)) {
        s = enc.get(PdfName.U).toString();
        strings.remove(enc.get(PdfName.U));
        uValue = com.itextpdf.text.DocWriter.getISOBytes(s);
        s = enc.get(PdfName.O).toString();
        strings.remove(enc.get(PdfName.O));
        oValue = com.itextpdf.text.DocWriter.getISOBytes(s);
        if (enc.contains(PdfName.OE))
            strings.remove(enc.get(PdfName.OE));
        if (enc.contains(PdfName.UE))
            strings.remove(enc.get(PdfName.UE));
        if (enc.contains(PdfName.PERMS))
            strings.remove(enc.get(PdfName.PERMS));

        o = enc.get(PdfName.P);
        if (!o.isNumber())
            throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.p.value"));
        pValue = ((PdfNumber) o).longValue();

        o = enc.get(PdfName.R);
        if (!o.isNumber())
            throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.r.value"));
        rValue = ((PdfNumber) o).intValue();

        switch (rValue) {
        case 2:
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
            break;
        case 3:
            o = enc.get(PdfName.LENGTH);
            if (!o.isNumber())
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            lengthValue = ((PdfNumber) o).intValue();
            if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            break;
        case 4:
            PdfDictionary dic = (PdfDictionary) enc.get(PdfName.CF);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("cf.not.found.encryption"));
            dic = (PdfDictionary) dic.get(PdfName.STDCF);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("stdcf.not.found.encryption"));
            if (PdfName.V2.equals(dic.get(PdfName.CFM)))
                cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            else if (PdfName.AESV2.equals(dic.get(PdfName.CFM)))
                cryptoMode = PdfWriter.ENCRYPTION_AES_128;
            else
                throw new UnsupportedPdfException(
                        MessageLocalization.getComposedMessage("no.compatible.encryption.found"));
            PdfObject em = enc.get(PdfName.ENCRYPTMETADATA);
            if (em != null && em.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
            break;
        case 5:
            cryptoMode = PdfWriter.ENCRYPTION_AES_256;
            PdfObject em5 = enc.get(PdfName.ENCRYPTMETADATA);
            if (em5 != null && em5.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
            break;
        default:
            throw new UnsupportedPdfException(
                    MessageLocalization.getComposedMessage("unknown.encryption.type.r.eq.1", rValue));
        }
    } else if (filter.equals(PdfName.PUBSEC)) {
        boolean foundRecipient = false;
        byte[] envelopedData = null;
        PdfArray recipients = null;

        o = enc.get(PdfName.V);
        if (!o.isNumber())
            throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.v.value"));
        int vValue = ((PdfNumber) o).intValue();
        switch (vValue) {
        case 1:
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
            lengthValue = 40;
            recipients = (PdfArray) enc.get(PdfName.RECIPIENTS);
            break;
        case 2:
            o = enc.get(PdfName.LENGTH);
            if (!o.isNumber())
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            lengthValue = ((PdfNumber) o).intValue();
            if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            recipients = (PdfArray) enc.get(PdfName.RECIPIENTS);
            break;
        case 4:
        case 5:
            PdfDictionary dic = (PdfDictionary) enc.get(PdfName.CF);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("cf.not.found.encryption"));
            dic = (PdfDictionary) dic.get(PdfName.DEFAULTCRYPTFILTER);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("defaultcryptfilter.not.found.encryption"));
            if (PdfName.V2.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
                lengthValue = 128;
            } else if (PdfName.AESV2.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.ENCRYPTION_AES_128;
                lengthValue = 128;
            } else if (PdfName.AESV3.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.ENCRYPTION_AES_256;
                lengthValue = 256;
            } else
                throw new UnsupportedPdfException(
                        MessageLocalization.getComposedMessage("no.compatible.encryption.found"));
            PdfObject em = dic.get(PdfName.ENCRYPTMETADATA);
            if (em != null && em.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;

            recipients = (PdfArray) dic.get(PdfName.RECIPIENTS);
            break;
        default:
            throw new UnsupportedPdfException(
                    MessageLocalization.getComposedMessage("unknown.encryption.type.v.eq.1", vValue));
        }
        X509CertificateHolder certHolder;
        try {
            certHolder = new X509CertificateHolder(certificate.getEncoded());
        } catch (Exception f) {
            throw new ExceptionConverter(f);
        }
        if (externalDecryptionProcess == null) {
            for (int i = 0; i < recipients.size(); i++) {
                PdfObject recipient = recipients.getPdfObject(i);
                strings.remove(recipient);

                CMSEnvelopedData data = null;
                try {
                    data = new CMSEnvelopedData(recipient.getBytes());

                    Iterator<RecipientInformation> recipientCertificatesIt = data.getRecipientInfos()
                            .getRecipients().iterator();

                    while (recipientCertificatesIt.hasNext()) {
                        RecipientInformation recipientInfo = recipientCertificatesIt.next();

                        if (recipientInfo.getRID().match(certHolder) && !foundRecipient) {
                            envelopedData = PdfEncryptor.getContent(recipientInfo, (PrivateKey) certificateKey,
                                    certificateKeyProvider);
                            foundRecipient = true;
                        }
                    }

                } catch (Exception f) {
                    throw new ExceptionConverter(f);
                }
            }
        } else {
            for (int i = 0; i < recipients.size(); i++) {
                PdfObject recipient = recipients.getPdfObject(i);
                strings.remove(recipient);

                CMSEnvelopedData data = null;
                try {
                    data = new CMSEnvelopedData(recipient.getBytes());

                    RecipientInformation recipientInfo = data.getRecipientInfos()
                            .get(externalDecryptionProcess.getCmsRecipientId());

                    if (recipientInfo != null) {
                        envelopedData = recipientInfo.getContent(externalDecryptionProcess.getCmsRecipient());
                        foundRecipient = true;
                    }
                } catch (Exception f) {
                    throw new ExceptionConverter(f);
                }
            }
        }

        if (!foundRecipient || envelopedData == null) {
            throw new UnsupportedPdfException(
                    MessageLocalization.getComposedMessage("bad.certificate.and.key"));
        }

        MessageDigest md = null;

        try {
            if ((cryptoMode & PdfWriter.ENCRYPTION_MASK) == PdfWriter.ENCRYPTION_AES_256)
                md = MessageDigest.getInstance("SHA-256");
            else
                md = MessageDigest.getInstance("SHA-1");
            md.update(envelopedData, 0, 20);
            for (int i = 0; i < recipients.size(); i++) {
                byte[] encodedRecipient = recipients.getPdfObject(i).getBytes();
                md.update(encodedRecipient);
            }
            if ((cryptoMode & PdfWriter.DO_NOT_ENCRYPT_METADATA) != 0)
                md.update(new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 });
            encryptionKey = md.digest();
        } catch (Exception f) {
            throw new ExceptionConverter(f);
        }
    }

    decrypt = new PdfEncryption();
    decrypt.setCryptoMode(cryptoMode, lengthValue);

    if (filter.equals(PdfName.STANDARD)) {
        if (rValue == 5) {
            ownerPasswordUsed = decrypt.readKey(enc, password);
            pValue = decrypt.getPermissions();
        } else {
            //check by owner password
            decrypt.setupByOwnerPassword(documentID, password, uValue, oValue, pValue);
            if (!equalsArray(uValue, decrypt.userKey, rValue == 3 || rValue == 4 ? 16 : 32)) {
                //check by user password
                decrypt.setupByUserPassword(documentID, password, oValue, pValue);
                if (!equalsArray(uValue, decrypt.userKey, rValue == 3 || rValue == 4 ? 16 : 32)) {
                    throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password"));
                }
            } else
                ownerPasswordUsed = true;
        }
    } else if (filter.equals(PdfName.PUBSEC)) {
        if ((cryptoMode & PdfWriter.ENCRYPTION_MASK) == PdfWriter.ENCRYPTION_AES_256)
            decrypt.setKey(encryptionKey);
        else
            decrypt.setupByEncryptionKey(encryptionKey, lengthValue);
        ownerPasswordUsed = true;
    }

    for (int k = 0; k < strings.size(); ++k) {
        PdfString str = strings.get(k);
        str.decrypt(this);
    }

    if (encDic.isIndirect()) {
        cryptoRef = (PRIndirectReference) encDic;
        xrefObj.set(cryptoRef.getNumber(), null);
    }
    encryptionError = false;
}

From source file:com.spilowagie.text.pdf.PdfReader.java

License:Mozilla Public License

/**
 * @throws IOException//from  w  w  w  .  j  a va2 s  .  c  om
 */
private void readDecryptedDocObj() throws IOException {
    if (encrypted)
        return;
    PdfObject encDic = trailer.get(PdfName.ENCRYPT);
    if (encDic == null || encDic.toString().equals("null"))
        return;
    encryptionError = true;
    byte[] encryptionKey = null;
    encrypted = true;
    PdfDictionary enc = (PdfDictionary) getPdfObject(encDic);

    String s;
    PdfObject o;

    PdfArray documentIDs = trailer.getAsArray(PdfName.ID);
    byte documentID[] = null;
    if (documentIDs != null) {
        o = documentIDs.getPdfObject(0);
        strings.remove(o);
        s = o.toString();
        documentID = com.spilowagie.text.DocWriter.getISOBytes(s);
        if (documentIDs.size() > 1)
            strings.remove(documentIDs.getPdfObject(1));
    }
    // just in case we have a broken producer
    if (documentID == null)
        documentID = new byte[0];
    byte uValue[] = null;
    byte oValue[] = null;
    int cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
    int lengthValue = 0;

    PdfObject filter = getPdfObjectRelease(enc.get(PdfName.FILTER));

    if (filter.equals(PdfName.STANDARD)) {
        s = enc.get(PdfName.U).toString();
        strings.remove(enc.get(PdfName.U));
        uValue = com.spilowagie.text.DocWriter.getISOBytes(s);
        s = enc.get(PdfName.O).toString();
        strings.remove(enc.get(PdfName.O));
        oValue = com.spilowagie.text.DocWriter.getISOBytes(s);

        o = enc.get(PdfName.P);
        if (!o.isNumber())
            throw new InvalidPdfException("Illegal P value.");
        pValue = ((PdfNumber) o).intValue();

        o = enc.get(PdfName.R);
        if (!o.isNumber())
            throw new InvalidPdfException("Illegal R value.");
        rValue = ((PdfNumber) o).intValue();

        switch (rValue) {
        case 2:
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
            break;
        case 3:
            o = enc.get(PdfName.LENGTH);
            if (!o.isNumber())
                throw new InvalidPdfException("Illegal Length value.");
            lengthValue = ((PdfNumber) o).intValue();
            if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
                throw new InvalidPdfException("Illegal Length value.");
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            break;
        case 4:
            PdfDictionary dic = (PdfDictionary) enc.get(PdfName.CF);
            if (dic == null)
                throw new InvalidPdfException("/CF not found (encryption)");
            dic = (PdfDictionary) dic.get(PdfName.STDCF);
            if (dic == null)
                throw new InvalidPdfException("/StdCF not found (encryption)");
            if (PdfName.V2.equals(dic.get(PdfName.CFM)))
                cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            else if (PdfName.AESV2.equals(dic.get(PdfName.CFM)))
                cryptoMode = PdfWriter.ENCRYPTION_AES_128;
            else
                throw new UnsupportedPdfException("No compatible encryption found");
            PdfObject em = enc.get(PdfName.ENCRYPTMETADATA);
            if (em != null && em.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
            break;
        default:
            throw new UnsupportedPdfException("Unknown encryption type R = " + rValue);
        }
    } else if (filter.equals(PdfName.PUBSEC)) {
        boolean foundRecipient = false;
        byte[] envelopedData = null;
        PdfArray recipients = null;

        o = enc.get(PdfName.V);
        if (!o.isNumber())
            throw new InvalidPdfException("Illegal V value.");
        int vValue = ((PdfNumber) o).intValue();
        switch (vValue) {
        case 1:
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
            lengthValue = 40;
            recipients = (PdfArray) enc.get(PdfName.RECIPIENTS);
            break;
        case 2:
            o = enc.get(PdfName.LENGTH);
            if (!o.isNumber())
                throw new InvalidPdfException("Illegal Length value.");
            lengthValue = ((PdfNumber) o).intValue();
            if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
                throw new InvalidPdfException("Illegal Length value.");
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            recipients = (PdfArray) enc.get(PdfName.RECIPIENTS);
            break;
        case 4:
            PdfDictionary dic = (PdfDictionary) enc.get(PdfName.CF);
            if (dic == null)
                throw new InvalidPdfException("/CF not found (encryption)");
            dic = (PdfDictionary) dic.get(PdfName.DEFAULTCRYPTFILTER);
            if (dic == null)
                throw new InvalidPdfException("/DefaultCryptFilter not found (encryption)");
            if (PdfName.V2.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
                lengthValue = 128;
            } else if (PdfName.AESV2.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.ENCRYPTION_AES_128;
                lengthValue = 128;
            } else
                throw new UnsupportedPdfException("No compatible encryption found");
            PdfObject em = dic.get(PdfName.ENCRYPTMETADATA);
            if (em != null && em.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;

            recipients = (PdfArray) dic.get(PdfName.RECIPIENTS);
            break;
        default:
            throw new UnsupportedPdfException("Unknown encryption type V = " + rValue);
        }
        for (int i = 0; i < recipients.size(); i++) {
            PdfObject recipient = recipients.getPdfObject(i);
            strings.remove(recipient);

            CMSEnvelopedData data = null;
            try {
                data = new CMSEnvelopedData(recipient.getBytes());

                Iterator recipientCertificatesIt = data.getRecipientInfos().getRecipients().iterator();

                while (recipientCertificatesIt.hasNext()) {
                    RecipientInformation recipientInfo = (RecipientInformation) recipientCertificatesIt.next();

                    if (recipientInfo.getRID().match(certificate) && !foundRecipient) {
                        envelopedData = recipientInfo.getContent(certificateKey, certificateKeyProvider);
                        foundRecipient = true;
                    }
                }
            } catch (Exception f) {
                throw new ExceptionConverter(f);
            }
        }

        if (!foundRecipient || envelopedData == null) {
            throw new UnsupportedPdfException("Bad certificate and key.");
        }

        MessageDigest md = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update(envelopedData, 0, 20);
            for (int i = 0; i < recipients.size(); i++) {
                byte[] encodedRecipient = recipients.getPdfObject(i).getBytes();
                md.update(encodedRecipient);
            }
            if ((cryptoMode & PdfWriter.DO_NOT_ENCRYPT_METADATA) != 0)
                md.update(new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 });
            encryptionKey = md.digest();
        } catch (Exception f) {
            throw new ExceptionConverter(f);
        }
    }

    decrypt = new PdfEncryption();
    decrypt.setCryptoMode(cryptoMode, lengthValue);

    if (filter.equals(PdfName.STANDARD)) {
        //check by owner password
        decrypt.setupByOwnerPassword(documentID, password, uValue, oValue, pValue);
        if (!equalsArray(uValue, decrypt.userKey, (rValue == 3 || rValue == 4) ? 16 : 32)) {
            //check by user password
            decrypt.setupByUserPassword(documentID, password, oValue, pValue);
            if (!equalsArray(uValue, decrypt.userKey, (rValue == 3 || rValue == 4) ? 16 : 32)) {
                throw new BadPasswordException("Bad user password");
            }
        } else
            ownerPasswordUsed = true;
    } else if (filter.equals(PdfName.PUBSEC)) {
        decrypt.setupByEncryptionKey(encryptionKey, lengthValue);
        ownerPasswordUsed = true;
    }

    for (int k = 0; k < strings.size(); ++k) {
        PdfString str = (PdfString) strings.get(k);
        str.decrypt(this);
    }

    if (encDic.isIndirect()) {
        cryptoRef = (PRIndirectReference) encDic;
        xrefObj.set(cryptoRef.getNumber(), null);
    }
    encryptionError = false;
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**
 * Decrypts the data of a message with all given certificates etc
 *
 * @param info MessageInfo, the encryption algorith will be stored in the
 * encryption type of this info/* ww w  .java 2 s  .  c  om*/
 * @param rawMessageData encrypted data, will be decrypted
 * @param contentType contentType of the data
 * @param privateKey receivers private key
 * @param certificate receivers certificate
 */
public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver,
        X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeBodyPart encryptedBody = new MimeBodyPart();
    encryptedBody.setHeader("content-type", contentType);
    encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    JceKeyTransRecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver);
    SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody);
    BCCryptoHelper helper = new BCCryptoHelper();
    String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID());
    if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_3DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_128);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_192);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_256);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN);
    } else {
        info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM);
    }
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    enveloped = null;
    encryptedBody = null;
    RecipientInformation recipient = recipients.get(recipientId);
    if (recipient == null) {
        //give some details about the required and used cert for the decryption
        Collection recipientList = recipients.getRecipients();
        Iterator iterator = recipientList.iterator();
        while (iterator.hasNext()) {
            RecipientInformation recipientInfo = (RecipientInformation) iterator.next();
            if (this.logger != null) {
                this.logger.log(Level.SEVERE,
                        this.rb.getResourceString("decryption.inforequired", new Object[] { info.getMessageId(),
                                ((KeyTransRecipientId) recipientInfo.getRID()).getIssuer() + ", "
                                        + ((KeyTransRecipientId) recipientInfo.getRID()).getSerialNumber() }),
                        info);
            }
        }
        if (this.logger != null) {
            this.logger.log(
                    Level.SEVERE, this.rb
                            .getResourceString("decryption.infoassigned",
                                    new Object[] { info.getMessageId(), receiverCryptAlias,
                                            recipientId.getIssuer() + ", " + recipientId.getSerialNumber() }),
                    info);
        }
        throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR,
                "Error decrypting the message: Recipient certificate does not match.", message);
    }
    //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses
    //far more memory.
    InputStream contentStream = recipient
            .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC"))
            .getContentStream();
    //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream();
    //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk
    DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_",
            ".mem", null);
    this.copyStreams(contentStream, decryptedOutput);
    decryptedOutput.flush();
    decryptedOutput.close();
    contentStream.close();
    byte[] decryptedData = null;
    //size of the data was < than the threshold
    if (decryptedOutput.isInMemory()) {
        decryptedData = decryptedOutput.getData();
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        decryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = decryptedOutput.getFile().delete();
        decryptedData = memOut.toByteArray();
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("decryption.done.alias",
                        new Object[] { info.getMessageId(), receiverCryptAlias,
                                this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }),
                info);
    }
    return (decryptedData);
}

From source file:io.aos.crypto.spl09.KeyTransEnvelopedDataWithCertMatchExample.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];

    // set up the generator
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

    gen.addKeyTransRecipient(cert);/*from  w  w w.j  a v  a 2 s  . c o  m*/

    // create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES256_CBC, "BC");

    // recreate
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    // set up to iterate through the recipients
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    CertStore certStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Collections.singleton(cert)), "BC");
    Iterator it = recipients.getRecipients().iterator();
    RecipientInformation recipient = null;

    while (it.hasNext()) {
        recipient = (RecipientInformation) it.next();
        if (recipient instanceof KeyTransRecipientInformation) {
            // match the recipient ID
            Collection matches = certStore.getCertificates(recipient.getRID());

            if (!matches.isEmpty()) {
                // decrypt the data
                byte[] recData = recipient.getContent(key, "BC");

                // compare recovered data to the original data
                if (Arrays.equals((byte[]) data.getContent(), recData)) {
                    System.out.println("data recovery succeeded");
                    break;
                } else {
                    System.out.println("data recovery failed");
                    break;
                }
            }
        }
    }

    if (recipient == null) {
        System.out.println("could not find a matching recipient");
    }
}

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  www .j  av  a2 s. c  om
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   www  . j a va2s  .  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);
        }
    }
}