Search in sources :

Example 36 with COSString

use of com.tom_roush.pdfbox.cos.COSString in project PdfBox-Android by TomRoush.

the class PDChoice method getValueFor.

/**
 * Returns the selected values, or an empty List, for the given key.
 */
private List<String> getValueFor(COSName name) {
    COSBase value = getCOSObject().getDictionaryObject(name);
    if (value instanceof COSString) {
        List<String> array = new ArrayList<String>();
        array.add(((COSString) value).getString());
        return array;
    } else if (value instanceof COSArray) {
        return COSArrayList.convertCOSStringCOSArrayToList((COSArray) value);
    }
    return Collections.emptyList();
}
Also used : COSArray(com.tom_roush.pdfbox.cos.COSArray) COSArrayList(com.tom_roush.pdfbox.pdmodel.common.COSArrayList) ArrayList(java.util.ArrayList) COSBase(com.tom_roush.pdfbox.cos.COSBase) COSString(com.tom_roush.pdfbox.cos.COSString) COSString(com.tom_roush.pdfbox.cos.COSString)

Example 37 with COSString

use of com.tom_roush.pdfbox.cos.COSString in project PdfBox-Android by TomRoush.

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 com.tom_roush.pdfbox.cos.COSDocument#getDocumentID()} (not used by
 * this handler)
 * @param decryptionMaterial Information used to decrypt the document.
 *
 * @throws IOException If there is an error accessing data. If verbose mode
 * is enabled, the exception message will provide more details why the
 * match wasn't successful.
 */
@Override
public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray, DecryptionMaterial decryptionMaterial) throws IOException {
    if (!(decryptionMaterial instanceof PublicKeyDecryptionMaterial)) {
        throw new IOException("Provided decryption material is not compatible with the document");
    }
    setDecryptMetadata(encryption.isEncryptMetaData());
    if (encryption.getLength() != 0) {
        this.keyLength = encryption.getLength();
    }
    PublicKeyDecryptionMaterial material = (PublicKeyDecryptionMaterial) decryptionMaterial;
    try {
        boolean foundRecipient = false;
        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 = (COSArray) encryption.getCOSObject().getItem(COSName.RECIPIENTS);
        if (array == null) {
            PDCryptFilterDictionary defaultCryptFilterDictionary = encryption.getDefaultCryptFilterDictionary();
            array = (COSArray) defaultCryptFilterDictionary.getCOSObject().getItem(COSName.RECIPIENTS);
        }
        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) {
            mdResult = MessageDigests.getSHA256().digest(sha1Input);
            // detect whether AES encryption is used. This assumes that the encryption algo is
            // stored in the PDCryptFilterDictionary
            // However, crypt filters are used only when V is 4 or 5.
            PDCryptFilterDictionary defaultCryptFilterDictionary = encryption.getDefaultCryptFilterDictionary();
            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 ...
        encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, encryptionKey, 0, this.keyLength / 8);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (KeyStoreException e) {
        throw new IOException(e);
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    }
}
Also used : CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) KeyTransRecipientId(org.bouncycastle.cms.KeyTransRecipientId) RecipientId(org.bouncycastle.cms.RecipientId) PrivateKey(java.security.PrivateKey) KeyTransRecipientId(org.bouncycastle.cms.KeyTransRecipientId) 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) COSArray(com.tom_roush.pdfbox.cos.COSArray) COSName(com.tom_roush.pdfbox.cos.COSName) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) COSString(com.tom_roush.pdfbox.cos.COSString) CMSException(org.bouncycastle.cms.CMSException)

Example 38 with COSString

use of com.tom_roush.pdfbox.cos.COSString in project PdfBox-Android by TomRoush.

the class PublicKeySecurityHandler method prepareEncryptionDictAES.

private void prepareEncryptionDictAES(PDEncryption encryptionDictionary, COSName aesVName, byte[][] recipients) {
    PDCryptFilterDictionary cryptFilterDictionary = new PDCryptFilterDictionary();
    cryptFilterDictionary.setCryptFilterMethod(aesVName);
    cryptFilterDictionary.setLength(keyLength);
    COSArray array = new COSArray();
    for (byte[] recipient : recipients) {
        array.add(new COSString(recipient));
    }
    cryptFilterDictionary.getCOSObject().setItem(COSName.RECIPIENTS, array);
    array.setDirect(true);
    encryptionDictionary.setDefaultCryptFilterDictionary(cryptFilterDictionary);
    encryptionDictionary.setStreamFilterName(COSName.DEFAULT_CRYPT_FILTER);
    encryptionDictionary.setStringFilterName(COSName.DEFAULT_CRYPT_FILTER);
    cryptFilterDictionary.getCOSObject().setDirect(true);
    setAES(true);
}
Also used : COSArray(com.tom_roush.pdfbox.cos.COSArray) COSString(com.tom_roush.pdfbox.cos.COSString)

Example 39 with COSString

use of com.tom_roush.pdfbox.cos.COSString in project PdfBox-Android by TomRoush.

the class SecurityHandler method decryptDictionary.

/**
 * This will decrypt a dictionary.
 *
 * @param dictionary The dictionary to decrypt.
 * @param objNum The object number.
 * @param genNum The object generation number.
 *
 * @throws IOException If there is an error creating a new string.
 */
private void decryptDictionary(COSDictionary dictionary, long objNum, long genNum) throws IOException {
    if (dictionary.getItem(COSName.CF) != null) {
        // PDFBOX-2936: avoid orphan /CF dictionaries found in US govt "I-" files
        return;
    }
    COSBase type = dictionary.getDictionaryObject(COSName.TYPE);
    boolean isSignature = COSName.SIG.equals(type) || COSName.DOC_TIME_STAMP.equals(type) || // https://ec.europa.eu/cefdigital/tracker/browse/DSS-1538
    (dictionary.getDictionaryObject(COSName.CONTENTS) instanceof COSString && dictionary.getDictionaryObject(COSName.BYTERANGE) instanceof COSArray);
    for (Map.Entry<COSName, COSBase> entry : dictionary.entrySet()) {
        if (isSignature && COSName.CONTENTS.equals(entry.getKey())) {
            // do not decrypt the signature contents string
            continue;
        }
        COSBase value = entry.getValue();
        // within a dictionary only the following kind of COS objects have to be decrypted
        if (value instanceof COSString || value instanceof COSArray || value instanceof COSDictionary) {
            decrypt(value, objNum, genNum);
        }
    }
}
Also used : COSArray(com.tom_roush.pdfbox.cos.COSArray) COSName(com.tom_roush.pdfbox.cos.COSName) COSDictionary(com.tom_roush.pdfbox.cos.COSDictionary) COSBase(com.tom_roush.pdfbox.cos.COSBase) COSString(com.tom_roush.pdfbox.cos.COSString) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap)

Example 40 with COSString

use of com.tom_roush.pdfbox.cos.COSString in project PdfBox-Android by TomRoush.

the class PDEncryption method getOwnerEncryptionKey.

/**
 * This will get the OE entry in the standard encryption dictionary.
 *
 * @return A 32 byte array or null if there is no owner encryption key.
 *
 * @throws IOException If there is an error accessing the data.
 */
public byte[] getOwnerEncryptionKey() throws IOException {
    byte[] oe = null;
    COSString ownerEncryptionKey = (COSString) dictionary.getDictionaryObject(COSName.OE);
    if (ownerEncryptionKey != null) {
        oe = ownerEncryptionKey.getBytes();
    }
    return oe;
}
Also used : COSString(com.tom_roush.pdfbox.cos.COSString)

Aggregations

COSString (com.tom_roush.pdfbox.cos.COSString)65 COSArray (com.tom_roush.pdfbox.cos.COSArray)33 COSBase (com.tom_roush.pdfbox.cos.COSBase)24 Test (org.junit.Test)9 ArrayList (java.util.ArrayList)8 IOException (java.io.IOException)7 COSDictionary (com.tom_roush.pdfbox.cos.COSDictionary)5 COSName (com.tom_roush.pdfbox.cos.COSName)5 COSArrayList (com.tom_roush.pdfbox.pdmodel.common.COSArrayList)4 Map (java.util.Map)4 COSBoolean (com.tom_roush.pdfbox.cos.COSBoolean)2 COSFloat (com.tom_roush.pdfbox.cos.COSFloat)2 COSInteger (com.tom_roush.pdfbox.cos.COSInteger)2 PDResources (com.tom_roush.pdfbox.pdmodel.PDResources)2 MessageDigest (java.security.MessageDigest)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Operator (com.tom_roush.pdfbox.contentstream.operator.Operator)1