Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelogs/4.0.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* **PDF/A extension schemas and Factur-X metadata (PR #1808).** `PdfWriter.addXmpSchema(XmpSchema, PdfAExtensionSchema.Schema)` adds custom XMP properties and the PDF/A extension schema that describes them to the metadata of `createXmpMetadata()`. `FacturXSchema` has the `fx` properties of ZUGFeRD and Factur-X invoices, so that a PDF/A-3 invoice with the invoice XML as an associated file passes veraPDF.
* **PDF/X-4 (PR #1809).** `PdfWriter.PDFX4` creates PDF/X-4 (ISO 15930-7:2010) documents for print production, with transparency, layers and ICC based colour. OpenPDF writes PDF 1.6, the PDF/X-4 identification and media management properties in the XMP metadata and `/GTS_PDFXVersion` and `/Trapped` in the info dictionary, and requires an output intent with an ICC profile and embedded fonts.
* **CMYK colour conversion (PR #1811).** `CmykColorConverter` converts RGB colours and images to the CMYK colour space of a printing condition with its ICC profile, for example ISOnewspaper26v4 or FOGRA39, and sets that profile as the output intent. An image with transparency gets a soft mask. This prepares content for PDF/X-4 and PDF/A with a CMYK output intent.
* **Post-quantum and AES-256 certificate encryption (PR #1815).** Documents encrypted for certificates with `PdfWriter.setEncryption(Certificate[], int[], int)` or `PdfStamper.setEncryption` can use `PdfWriter.ENCRYPTION_AES_256_V3`, the AES-256 public-key security handler of ISO 32000-2 (`/V 5`, `/AESV3`, SHA-256 key derivation), and `PdfReader` decrypts such documents. A recipient certificate with an ML-KEM (FIPS 203) public key gets a CMS `KEMRecipientInfo` (RFC 9629, RFC 9936) instead of RSA key transport, so the document key stays confidential against an attacker with a quantum computer. Documents for ML-KEM recipients can be read with OpenPDF and other CMS implementations that support ML-KEM, but not yet with Adobe Acrobat.

## 🛠 Bug Fixes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,40 @@
import java.io.IOException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.util.Collection;
import java.util.List;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.KEMRecipientInformation;
import org.bouncycastle.cms.Recipient;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.jcajce.JceKEMEnvelopedRecipient;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class BouncyCastleHelper {

/**
* The Bouncy Castle provider of the post-quantum key encapsulation, created when it is first used. It is not
* registered with {@link java.security.Security}, so that the providers of the application stay as they are.
*/
private static final class ProviderHolder {

private static final Provider PROVIDER = new BouncyCastleProvider();
}

/**
* Returns the Bouncy Castle provider, which implements the ML-KEM key wrapping of CMS.
*
* @return the Bouncy Castle provider
*/
public static Provider getProvider() {
return ProviderHolder.PROVIDER;
}

public static void checkCertificateEncodingOrThrowException(Certificate certificate) {
// OJO...
try {
Expand All @@ -43,12 +66,8 @@ public static byte[] getEnvelopedData(PdfArray recipients, List<PdfObject> strin
if (recipientInfo.getRID().match(certificateHolder)) {
// OJO...
// https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cms/CMSEnvelopedData.html
JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(
(PrivateKey) certificateKey);
if (certificateKeyProvider != null) {
rec.setProvider(certificateKeyProvider);
}
envelopedData = recipientInfo.getContent(rec);
envelopedData = recipientInfo.getContent(
createRecipient(recipientInfo, (PrivateKey) certificateKey, certificateKeyProvider));
// ******************************************************************************
break;
}
Expand All @@ -60,4 +79,25 @@ public static byte[] getEnvelopedData(PdfArray recipients, List<PdfObject> strin
}
return envelopedData;
}

/**
* Creates the recipient that decrypts the content encryption key: a KEM recipient for a post-quantum key such as
* ML-KEM (RFC 9629 and RFC 9936), a key transport recipient for RSA.
*/
private static Recipient createRecipient(RecipientInformation recipientInfo, PrivateKey key, String provider) {
if (recipientInfo instanceof KEMRecipientInformation) {
JceKEMEnvelopedRecipient recipient = new JceKEMEnvelopedRecipient(key);
if (provider != null) {
recipient.setProvider(provider);
} else {
recipient.setProvider(getProvider());
}
return recipient;
}
JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient(key);
if (provider != null) {
recipient.setProvider(provider);
}
return recipient;
}
}
29 changes: 21 additions & 8 deletions openpdf-core/src/main/java/org/openpdf/text/pdf/PdfEncryption.java
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,11 @@
public void setupByEncryptionKey(byte[] key, int keylength) {
mkey = new byte[keylength / 8];
System.arraycopy(key, 0, mkey, 0, mkey.length);
if (revision >= AES_256_V3) {
// AESV3 uses the file encryption key for all objects, as setHashKey does not derive object keys
this.key = mkey.clone();
keySize = mkey.length;
}
}

public void setHashKey(int number, int generation) {
Expand Down Expand Up @@ -617,20 +622,27 @@
dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4);
dic.put(PdfName.RECIPIENTS, recipients);
} else {
dic.put(PdfName.R, new PdfNumber(AES_128));
dic.put(PdfName.V, new PdfNumber(4));
dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5);

PdfDictionary stdcf = new PdfDictionary();
stdcf.put(PdfName.RECIPIENTS, recipients);
if (!encryptMetadata) {
stdcf.put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE);
}

if (revision == AES_128) {
stdcf.put(PdfName.CFM, PdfName.AESV2);
dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5);
if (revision == AES_256_V3) {
// ISO 32000-2, 7.6.5.3: AES-256 crypt filter of the public-key security handler
dic.put(PdfName.V, new PdfNumber(5));
dic.put(PdfName.LENGTH, new PdfNumber(256));
stdcf.put(PdfName.CFM, PdfName.AESV3);
stdcf.put(PdfName.LENGTH, new PdfNumber(256));
} else {
stdcf.put(PdfName.CFM, PdfName.V2);
dic.put(PdfName.R, new PdfNumber(AES_128));
dic.put(PdfName.V, new PdfNumber(4));
if (revision == AES_128) {
stdcf.put(PdfName.CFM, PdfName.AESV2);
} else {
stdcf.put(PdfName.CFM, PdfName.V2);
}
}
PdfDictionary cf = new PdfDictionary();
cf.put(PdfName.DEFAULTCRYPTFILTER, stdcf);
Expand All @@ -649,7 +661,8 @@
byte[] encodedRecipient = null;

try {
md = MessageDigest.getInstance("SHA-1");
// ISO 32000-2, 7.6.5.3: SHA-256 for AESV3, SHA-1 for the older crypt filters
md = MessageDigest.getInstance(revision == AES_256_V3 ? "SHA-256" : "SHA-1");

Check failure on line 665 in openpdf-core/src/main/java/org/openpdf/text/pdf/PdfEncryption.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal "SHA-256" 3 times.

See more on https://sonarcloud.io/project/issues?id=LibrePDF_OpenPDF&issues=AaI8M-dvZBQ17P4nGXCX&open=AaI8M-dvZBQ17P4nGXCX&pullRequest=1815
md.update(publicKeyHandler.getSeed());
for (int i = 0; i < publicKeyHandler.getRecipientsSize(); i++) {
encodedRecipient = publicKeyHandler.getEncodedRecipient(i);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,13 @@
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.bouncycastle.asn1.ASN1Encoding;
Expand All @@ -109,8 +111,11 @@
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.RecipientInfoGenerator;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.cms.jcajce.JceKEMRecipientInfoGenerator;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.openpdf.bouncycastle.BouncyCastleHelper;

/**
* @author Aiken Sam ([email protected])
Expand All @@ -119,6 +124,11 @@ public class PdfPublicKeySecurityHandler {

static final int SEED_LENGTH = 20;

/**
* Object identifiers of the ML-KEM algorithms of FIPS 203: ML-KEM-512, ML-KEM-768 and ML-KEM-1024.
*/
private static final String ML_KEM_OID_PREFIX = "2.16.840.1.101.3.4.4.";

private final List<PdfPublicKeyRecipient> recipients;

private byte[] seed = new byte[SEED_LENGTH];
Expand Down Expand Up @@ -220,15 +230,46 @@ public PdfArray getEncodedRecipients() throws IOException {
return encodedRecipients;
}

/**
* Tells if the public key is a post-quantum key encapsulation key (ML-KEM) rather than a key transport key such as
* RSA.
*
* @param publicKey the public key of a recipient
* @return {@code true} for an ML-KEM key
*/
static boolean isKemKey(PublicKey publicKey) {
String algorithm = publicKey.getAlgorithm();
if (algorithm == null) {
return false;
}
String name = algorithm.toUpperCase(Locale.ROOT).replace("_", "-");
return name.startsWith("ML-KEM") || name.startsWith("MLKEM") || algorithm.startsWith(ML_KEM_OID_PREFIX);
}

/**
* Creates the recipient info that encrypts the content encryption key for the holder of the certificate. For an
* ML-KEM certificate this is a {@code KEMRecipientInfo} (RFC 9629 and RFC 9936) that wraps the key with AES-256,
* so that the document stays confidential against an attacker with a quantum computer. For other certificates,
* such as RSA, it is a {@code KeyTransRecipientInfo}.
*/
private static RecipientInfoGenerator createRecipientInfoGenerator(X509Certificate cert)
throws GeneralSecurityException {
if (isKemKey(cert.getPublicKey())) {
return new JceKEMRecipientInfoGenerator(cert, CMSAlgorithm.AES256_WRAP)
.setProvider(BouncyCastleHelper.getProvider());
}
return new JceKeyTransRecipientInfoGenerator(cert);
}

/**
* Creates the enveloped data of one recipient. The content is encrypted with AES-256 and its key is
* encrypted with the public key of the certificate.
* encrypted with the public key of the certificate, or encapsulated with it for an ML-KEM certificate.
*/
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
throws GeneralSecurityException {
try {
CMSEnvelopedDataGenerator generator = new CMSEnvelopedDataGenerator();
generator.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cert));
generator.addRecipientInfoGenerator(createRecipientInfoGenerator(cert));
CMSEnvelopedData envelopedData = generator.generate(new CMSProcessableByteArray(in),
new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).build());
return envelopedData.toASN1Structure().toASN1Primitive();
Expand Down
32 changes: 29 additions & 3 deletions openpdf-core/src/main/java/org/openpdf/text/pdf/PdfReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -1595,7 +1595,7 @@
} else {
throw new UnsupportedPdfException(
MessageLocalization
.getComposedMessage("no.compatible.encryption.found"));

Check failure on line 1598 in openpdf-core/src/main/java/org/openpdf/text/pdf/PdfReader.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal "no.compatible.encryption.found" 3 times.

See more on https://sonarcloud.io/project/issues?id=LibrePDF_OpenPDF&issues=AaI8M-SaZBQ17P4nGXCW&open=AaI8M-SaZBQ17P4nGXCW&pullRequest=1815
}
PdfObject em = enc.get(PdfName.ENCRYPTMETADATA);
if (em != null && em.toString().equals(FALSE)) {
Expand Down Expand Up @@ -1674,26 +1674,52 @@

recipients = (PdfArray) dic.get(PdfName.RECIPIENTS);
}
case 5 -> {
PdfDictionary cf = enc.getAsDict(PdfName.CF);
PdfDictionary dic = cf == null ? null : cf.getAsDict(PdfName.DEFAULTCRYPTFILTER);
if (dic == null) {
throw new InvalidPdfException(
MessageLocalization
.getComposedMessage("defaultcryptfilter.not.found.encryption"));
}
if (!PdfName.AESV3.equals(dic.get(PdfName.CFM))) {
throw new UnsupportedPdfException(
MessageLocalization
.getComposedMessage("no.compatible.encryption.found"));
}
cryptoMode = PdfWriter.ENCRYPTION_AES_256_V3;
lengthValue = 256;
PdfObject em = dic.get(PdfName.ENCRYPTMETADATA);
if (em != null && em.toString().equals(FALSE)) {
cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
}
recipients = dic.getAsArray(PdfName.RECIPIENTS);
}
default -> {
throw new UnsupportedPdfException(
MessageLocalization.getComposedMessage(
"unknown.encryption.type.v.eq.1", rValue));
}
}
if (recipients == null) {
throw new InvalidPdfException(
MessageLocalization.getComposedMessage("bad.certificate.and.key"));
}
BouncyCastleHelper.checkCertificateEncodingOrThrowException(certificate);
byte[] envelopedData = BouncyCastleHelper.getEnvelopedData(recipients, strings, certificate, certificateKey,
certificateKeyProvider);

if (envelopedData == null) {
if (envelopedData == null || envelopedData.length < PdfPublicKeySecurityHandler.SEED_LENGTH) {
throw new UnsupportedPdfException(
MessageLocalization.getComposedMessage("bad.certificate.and.key"));
}

MessageDigest md;

try {
md = MessageDigest.getInstance("SHA-1");
md.update(envelopedData, 0, 20);
// ISO 32000-2, 7.6.5.3: SHA-256 for AESV3, SHA-1 for the older crypt filters
md = MessageDigest.getInstance(lengthValue == 256 ? "SHA-256" : "SHA-1");
md.update(envelopedData, 0, PdfPublicKeySecurityHandler.SEED_LENGTH);
for (int i = 0; i < recipients.size(); i++) {
byte[] encodedRecipient = recipients.getPdfObject(i).getBytes();
md.update(encodedRecipient);
Expand Down
Loading
Loading