Search in sources :

Example 1 with KeyTransRecipientId

use of org.bouncycastle.cms.KeyTransRecipientId 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");
    }
    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
        byte[][] recipientFieldsBytes = new byte[encryption.getRecipientsLength()][];
        int recipientFieldsLength = 0;
        int i = 0;
        StringBuilder extraInfo = new StringBuilder();
        for (; i < encryption.getRecipientsLength(); i++) {
            COSString recipientFieldString = encryption.getRecipientStringAt(i);
            byte[] recipientBytes = recipientFieldString.getBytes();
            CMSEnvelopedData data = new CMSEnvelopedData(recipientBytes);
            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();
                    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 " + i + " recipient entries" + extraInfo.toString());
        }
        if (envelopedData.length != 24) {
            throw new IOException("The enveloped data does not contain 24 bytes");
        }
        // now envelopedData contains:
        // - the 20 bytes seed
        // - the 4 bytes of permission for the current user
        byte[] accessBytes = new byte[4];
        System.arraycopy(envelopedData, 20, accessBytes, 0, 4);
        AccessPermission currentAccessPermission = new AccessPermission(accessBytes);
        currentAccessPermission.setReadOnly();
        setCurrentAccessPermission(currentAccessPermission);
        // what we will put in the SHA1 = the seed + each byte contained in the recipients array
        byte[] sha1Input = new byte[recipientFieldsLength + 20];
        // put the seed in the sha1 input
        System.arraycopy(envelopedData, 0, sha1Input, 0, 20);
        // put each bytes of the recipients array in the sha1 input
        int sha1InputOffset = 20;
        for (byte[] recipientFieldsByte : recipientFieldsBytes) {
            System.arraycopy(recipientFieldsByte, 0, sha1Input, sha1InputOffset, recipientFieldsByte.length);
            sha1InputOffset += recipientFieldsByte.length;
        }
        MessageDigest md = MessageDigests.getSHA1();
        byte[] mdResult = md.digest(sha1Input);
        // we have the encryption key ...
        encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, encryptionKey, 0, this.keyLength / 8);
    } catch (CMSException | KeyStoreException | 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) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) MessageDigest(java.security.MessageDigest) COSString(org.apache.pdfbox.cos.COSString) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

IOException (java.io.IOException)1 KeyStoreException (java.security.KeyStoreException)1 MessageDigest (java.security.MessageDigest)1 PrivateKey (java.security.PrivateKey)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 X509Certificate (java.security.cert.X509Certificate)1 COSString (org.apache.pdfbox.cos.COSString)1 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)1 CMSEnvelopedData (org.bouncycastle.cms.CMSEnvelopedData)1 CMSException (org.bouncycastle.cms.CMSException)1 KeyTransRecipientId (org.bouncycastle.cms.KeyTransRecipientId)1 RecipientId (org.bouncycastle.cms.RecipientId)1 RecipientInformation (org.bouncycastle.cms.RecipientInformation)1 JceKeyTransEnvelopedRecipient (org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient)1