Example usage for org.bouncycastle.cms CMSEnvelopedData getRecipientInfos

List of usage examples for org.bouncycastle.cms CMSEnvelopedData getRecipientInfos

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSEnvelopedData getRecipientInfos.

Prototype

public RecipientInformationStore getRecipientInfos() 

Source Link

Document

return a store of the intended recipients for this message

Usage

From source file:chapter9.KEKEnvelopedDataExample.java

/**
 *
 * @param args/*from  w w w. jav a  2s. c  o  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance(CryptoDefs.Algorithm.DESede.getName(),
            CryptoDefs.Provider.BC.getName());
    SecretKey key = keyGen.generateKey();

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

    byte[] kekID = new byte[] { 1, 2, 3, 4, 5 };

    edGen.addKEKRecipient(key, kekID);

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

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

    //4.- Look for our recipient identifier
    RecipientId recId = new KEKRecipientId(kekID);

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        //5.- Decrypt the data
        byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

        //6.- Compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData))
            System.out.println("\t data recovery succeeded!!");
        else
            System.out.println("\t data recovery failed!!");
    } else
        System.out.println("\t Could not find a matching recipient!!");
}

From source file:chapter9.KeyTransEnvelopedDataExample.java

/**
 *
 * @param args/*from  w ww .  j  av  a 2  s .  co  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
    RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()),
            cert.getSerialNumber());

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

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        //5.- Decrypt the data
        byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

        //6.- Compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData))
            System.out.println("\t data recovery succeeded!!");
        else
            System.out.println("\t data recovery failed!!");
    } else
        System.out.println("\t Could not find a matching recipient!!");
}

From source file:chapter9.KeyTransEnvelopedDataExample2.java

/**
 *
 * @param args/*from   w ww  . ja  v a2 s .  c  om*/
 * @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.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;//ww w.  j a v  a  2  s. 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 av  a2 s.c  om
 */
@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.maiereni.host.web.util.impl.BouncyCastleEncryptorImpl.java

License:Apache License

public byte[] decryptData(@Nonnull final byte[] encryptedData) throws Exception {
    CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData);
    Collection<RecipientInformation> recip = envelopedData.getRecipientInfos().getRecipients();
    KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recip.iterator().next();
    JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(key);
    return recipientInfo.getContent(recipient);
}

From source file:com.silverpeas.util.cryptage.SilverCryptFactoryAsymetric.java

License:Open Source License

public String goUnCrypting(byte[] stringCrypted, String fileName) throws CryptageException {
    try {//from  ww  w.j a  va2  s.c om
        // Chargement de la chaine  dchiffrer
        byte[] pkcs7envelopedData = stringCrypted;

        // Dchiffrement de la chaine
        CMSEnvelopedData ced = new CMSEnvelopedData(pkcs7envelopedData);
        @SuppressWarnings("unchecked")
        Collection<KeyTransRecipientInformation> recip = ced.getRecipientInfos().getRecipients();

        KeyTransRecipientInformation rinfo = recip.iterator().next();
        // privatekey est la cl prive permettant de dchiffrer la cl
        // secrte (symtrique)
        byte[] contents = rinfo
                .getContent(new JceKeyTransEnvelopedRecipient(this.getKeys(fileName).getPrivatekey()));
        return byteArrayToString(contents);
    } catch (CryptageException e) {
        throw e;
    } catch (Exception e) {
        throw new CryptageException("SilverCryptFactory.goUnCrypting", SilverpeasException.ERROR,
                "util.UNCRYPT_FAILED", e);
    }
}

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

License:Mozilla Public License

/**
 * @throws IOException/*w  w w. j  a  v  a  2  s  . c  o  m*/
 */
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:eu.inn.biometric.signature.crypto.BCCryptoProvider.java

License:Open Source License

@Override
public byte[] decrypt(byte[] data, PrivateKey key) {
    try {/*from  w  w w . j av a2  s.co  m*/

        CMSEnvelopedData enveloped = new CMSEnvelopedData(data);

        for (Object recip : enveloped.getRecipientInfos().getRecipients()) {
            try {
                KeyTransRecipientInformation rinfo = (KeyTransRecipientInformation) recip;
                byte[] decryptedDocument = rinfo.getContent(new JceKeyTransEnvelopedRecipient(key));
                return decryptedDocument;
            } catch (Exception ex) {
            }
        }
        throw new RuntimeException("Cannot decrypt");

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:io.aos.crypto.spl09.KEKEnvelopedDataExample.java

License:Apache License

public static void main(String... args) throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("DESEDE", "BC");
    SecretKey key = keyGen.generateKey();

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

    byte[] kekID = new byte[] { 1, 2, 3, 4, 5 };

    edGen.addKEKRecipient(key, kekID);/*from   ww  w.  ja va2  s. c  o m*/

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

    CMSEnvelopedData enveloped = edGen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, "BC");
    // recreate
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    // look for our recipient
    RecipientId recId = new KEKRecipientId(kekID);

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        // 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");
        } else {
            System.out.println("data recovery failed");
        }
    } else {
        System.out.println("could not find a matching recipient");
    }
}