Search in sources :

Example 6 with CMSEnvelopedData

use of org.bouncycastle.cms.CMSEnvelopedData in project tutorials by eugenp.

the class BouncyCastleCrypto method decryptData.

public static byte[] decryptData(final byte[] encryptedData, final PrivateKey decryptionKey) throws CMSException {
    byte[] decryptedData = null;
    if (null != encryptedData && null != decryptionKey) {
        CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData);
        Collection<RecipientInformation> recip = envelopedData.getRecipientInfos().getRecipients();
        KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recip.iterator().next();
        JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey);
        decryptedData = recipientInfo.getContent(recipient);
    }
    return decryptedData;
}
Also used : JceKeyTransRecipient(org.bouncycastle.cms.jcajce.JceKeyTransRecipient) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) KeyTransRecipientInformation(org.bouncycastle.cms.KeyTransRecipientInformation) RecipientInformation(org.bouncycastle.cms.RecipientInformation) KeyTransRecipientInformation(org.bouncycastle.cms.KeyTransRecipientInformation) JceKeyTransEnvelopedRecipient(org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient)

Example 7 with CMSEnvelopedData

use of org.bouncycastle.cms.CMSEnvelopedData in project tutorials by eugenp.

the class BouncyCastleCrypto method encryptData.

public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException {
    byte[] encryptedData = null;
    if (null != data && null != encryptionCertificate) {
        CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
        JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
        cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
        CMSTypedData msg = new CMSProcessableByteArray(data);
        OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build();
        CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
        encryptedData = cmsEnvelopedData.getEncoded();
    }
    return encryptedData;
}
Also used : CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) JceKeyTransRecipientInfoGenerator(org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSEnvelopedDataGenerator(org.bouncycastle.cms.CMSEnvelopedDataGenerator) CMSTypedData(org.bouncycastle.cms.CMSTypedData) JceCMSContentEncryptorBuilder(org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder) OutputEncryptor(org.bouncycastle.operator.OutputEncryptor)

Example 8 with CMSEnvelopedData

use of org.bouncycastle.cms.CMSEnvelopedData in project serverless by bluenimble.

the class DecryptDocument method main.

public static void main(String[] args) throws IOException, CertificateException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, CertStoreException, CMSException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
    CMSEnvelopedData ced = new CMSEnvelopedData(new FileInputStream("ToBeDecrypted.pk7"));
    Collection<?> recip = ced.getRecipientInfos().getRecipients();
    KeyTransRecipientInformation rinfo = (KeyTransRecipientInformation) recip.iterator().next();
    // privatekey est la cl� priv�e permettant de d�chiffrer la cl� secr�te (sym�trique)
    // "2[$0wUOS";
    String password = "bspass";
    // "thawte freemail member's thawte consulting (pty) ltd. id";
    String alias = "bscert";
    KeyInformation keyInfo = ReadPKCS12.read(new FileInputStream("files/test.p12"), password, alias);
    byte[] contents = rinfo.getContent(new JceKeyTransEnvelopedRecipient(keyInfo.getPrivateKey()).setProvider("BC"));
    FileOutputStream envfos = new FileOutputStream("Decrypted.txt");
    envfos.write(contents);
    envfos.close();
}
Also used : CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) FileOutputStream(java.io.FileOutputStream) KeyTransRecipientInformation(org.bouncycastle.cms.KeyTransRecipientInformation) JceKeyTransEnvelopedRecipient(org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient) FileInputStream(java.io.FileInputStream) KeyInformation(com.bluenimble.platform.crypto.tests.KeyInformation)

Example 9 with CMSEnvelopedData

use of org.bouncycastle.cms.CMSEnvelopedData in project pdfbox by apache.

the class PublicKeySecurityHandler method prepareForDecryption.

/**
 * Prepares everything to decrypt the document.
 *
 * @param encryption encryption dictionary, can be retrieved via
 * {@link PDDocument#getEncryption()}
 * @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 - " + "did you pass a null keyStore?");
    }
    PDCryptFilterDictionary defaultCryptFilterDictionary = encryption.getDefaultCryptFilterDictionary();
    if (defaultCryptFilterDictionary != null && defaultCryptFilterDictionary.getLength() != 0) {
        setKeyLength(defaultCryptFilterDictionary.getLength());
        setDecryptMetadata(defaultCryptFilterDictionary.isEncryptMetaData());
    } else if (encryption.getLength() != 0) {
        setKeyLength(encryption.getLength());
        setDecryptMetadata(encryption.isEncryptMetaData());
    }
    PublicKeyDecryptionMaterial material = (PublicKeyDecryptionMaterial) decryptionMaterial;
    try {
        boolean foundRecipient = false;
        X509Certificate certificate = material.getCertificate();
        X509CertificateHolder materialCert = null;
        if (certificate != null) {
            materialCert = new X509CertificateHolder(certificate.getEncoded());
        }
        // 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
        COSArray array = encryption.getCOSObject().getCOSArray(COSName.RECIPIENTS);
        if (array == null && defaultCryptFilterDictionary != null) {
            array = defaultCryptFilterDictionary.getCOSObject().getCOSArray(COSName.RECIPIENTS);
        }
        if (array == null) {
            throw new IOException("/Recipients entry is missing in encryption dictionary");
        }
        byte[][] recipientFieldsBytes = new byte[array.size()][];
        // TODO encryption.getRecipientsLength() and getRecipientStringAt() should be deprecated
        int recipientFieldsLength = 0;
        StringBuilder extraInfo = new StringBuilder();
        for (int i = 0; i < array.size(); i++) {
            COSString recipientFieldString = (COSString) array.getObject(i);
            byte[] recipientBytes = recipientFieldString.getBytes();
            CMSEnvelopedData data = new CMSEnvelopedData(recipientBytes);
            Collection<RecipientInformation> recipCertificatesIt = data.getRecipientInfos().getRecipients();
            int j = 0;
            for (RecipientInformation ri : recipCertificatesIt) {
                // Impl: if a matching certificate was previously found it is an error,
                // here we just don't care about it
                RecipientId rid = ri.getRID();
                if (!foundRecipient && rid.match(materialCert)) {
                    foundRecipient = true;
                    PrivateKey privateKey = (PrivateKey) material.getPrivateKey();
                    // might need to call setContentProvider() if we use PKI token, see
                    // http://bouncy-castle.1462172.n4.nabble.com/CMSException-exception-unwrapping-key-key-invalid-unknown-key-type-passed-to-RSA-td4658109.html
                    envelopedData = ri.getContent(new JceKeyTransEnvelopedRecipient(privateKey));
                    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 " + array.size() + " 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;
        }
        byte[] mdResult;
        if (encryption.getVersion() == 4 || encryption.getVersion() == 5) {
            if (!isDecryptMetadata()) {
                // "4 bytes with the value 0xFF if the key being generated is intended for use in
                // document-level encryption and the document metadata is being left as plaintext"
                sha1Input = Arrays.copyOf(sha1Input, sha1Input.length + 4);
                System.arraycopy(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }, 0, sha1Input, sha1Input.length - 4, 4);
            }
            if (encryption.getVersion() == 4) {
                mdResult = MessageDigests.getSHA1().digest(sha1Input);
            } else {
                mdResult = MessageDigests.getSHA256().digest(sha1Input);
            }
            // However, crypt filters are used only when V is 4 or 5.
            if (defaultCryptFilterDictionary != null) {
                COSName cryptFilterMethod = defaultCryptFilterDictionary.getCryptFilterMethod();
                setAES(COSName.AESV2.equals(cryptFilterMethod) || COSName.AESV3.equals(cryptFilterMethod));
            }
        } else {
            mdResult = MessageDigests.getSHA1().digest(sha1Input);
        }
        // we have the encryption key ...
        setEncryptionKey(new byte[getKeyLength() / 8]);
        System.arraycopy(mdResult, 0, getEncryptionKey(), 0, getKeyLength() / 8);
    } catch (CMSException | KeyStoreException | CertificateEncodingException e) {
        throw new IOException(e);
    }
}
Also used : KeyTransRecipientId(org.bouncycastle.cms.KeyTransRecipientId) RecipientId(org.bouncycastle.cms.RecipientId) PrivateKey(java.security.PrivateKey) KeyTransRecipientId(org.bouncycastle.cms.KeyTransRecipientId) COSArray(org.apache.pdfbox.cos.COSArray) COSName(org.apache.pdfbox.cos.COSName) COSString(org.apache.pdfbox.cos.COSString) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) JceKeyTransEnvelopedRecipient(org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) RecipientInformation(org.bouncycastle.cms.RecipientInformation) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

CMSEnvelopedData (org.bouncycastle.cms.CMSEnvelopedData)9 IOException (java.io.IOException)4 CertificateEncodingException (java.security.cert.CertificateEncodingException)4 X509Certificate (java.security.cert.X509Certificate)4 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)4 FileOutputStream (java.io.FileOutputStream)3 CMSException (org.bouncycastle.cms.CMSException)3 CMSTypedData (org.bouncycastle.cms.CMSTypedData)3 JceKeyTransEnvelopedRecipient (org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient)3 FileInputStream (java.io.FileInputStream)2 KeyStoreException (java.security.KeyStoreException)2 PrivateKey (java.security.PrivateKey)2 CertificateException (java.security.cert.CertificateException)2 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)2 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)2 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)2 CMSEnvelopedDataGenerator (org.bouncycastle.cms.CMSEnvelopedDataGenerator)2 KeyTransRecipientInformation (org.bouncycastle.cms.KeyTransRecipientInformation)2 RecipientInformation (org.bouncycastle.cms.RecipientInformation)2 JceCMSContentEncryptorBuilder (org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder)2