From da9235451a91f8230bbb13491c0ad1f82af1f580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20R=C3=B8sdal?= Date: Thu, 3 Dec 2026 14:56:00 +0100 Subject: [PATCH 1/3] Support AES-256 and post-quantum ML-KEM certificate encryption Documents encrypted for certificates can use ENCRYPTION_AES_256_V3, the AES-256 public-key security handler of ISO 32000-2 (V 5, AESV3, SHA-256 key derivation), for writing and reading. Before, this mode wrote a broken V 4 dictionary with the RC4 crypt filter. A recipient certificate with an ML-KEM (FIPS 203) public key gets a CMS KEMRecipientInfo (RFC 9629, RFC 9936) that wraps the content key with AES-256, so the document key is protected against quantum attacks. RSA recipients still use key transport, and both can share one document. Co-Authored-By: Claude Opus 5.5 --- changelogs/4.0.1.md | 1 + .../bouncycastle/BouncyCastleHelper.java | 52 ++++++- .../org/openpdf/text/pdf/PdfEncryption.java | 29 +++- .../text/pdf/PdfPublicKeySecurityHandler.java | 45 +++++- .../java/org/openpdf/text/pdf/PdfReader.java | 32 +++- .../text/pdf/PdfPublicKeyEncryptionTest.java | 145 +++++++++++++++++- 6 files changed, 282 insertions(+), 22 deletions(-) diff --git a/changelogs/4.0.1.md b/changelogs/4.0.1.md index a15bdfc37..45478f007 100644 --- a/changelogs/4.0.1.md +++ b/changelogs/4.0.1.md @@ -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.** 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 diff --git a/openpdf-core/src/main/java/org/openpdf/bouncycastle/BouncyCastleHelper.java b/openpdf-core/src/main/java/org/openpdf/bouncycastle/BouncyCastleHelper.java index 1e5998183..1aeb428f4 100644 --- a/openpdf-core/src/main/java/org/openpdf/bouncycastle/BouncyCastleHelper.java +++ b/openpdf-core/src/main/java/org/openpdf/bouncycastle/BouncyCastleHelper.java @@ -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 { @@ -43,12 +66,8 @@ public static byte[] getEnvelopedData(PdfArray recipients, List 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; } @@ -60,4 +79,25 @@ public static byte[] getEnvelopedData(PdfArray recipients, List 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; + } } diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfEncryption.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfEncryption.java index cd7517d24..e66327110 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfEncryption.java +++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfEncryption.java @@ -565,6 +565,11 @@ private void setupByOwnerPad(byte[] documentID, byte[] ownerPad, 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) { @@ -617,20 +622,27 @@ public PdfDictionary getEncryptionDictionary() { 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); @@ -649,7 +661,8 @@ public PdfDictionary getEncryptionDictionary() { 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"); md.update(publicKeyHandler.getSeed()); for (int i = 0; i < publicKeyHandler.getRecipientsSize(); i++) { encodedRecipient = publicKeyHandler.getEncodedRecipient(i); diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfPublicKeySecurityHandler.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfPublicKeySecurityHandler.java index 1b55e7ffb..d62823527 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfPublicKeySecurityHandler.java +++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfPublicKeySecurityHandler.java @@ -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; @@ -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 (aikensam@ieee.org) @@ -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 recipients; private byte[] seed = new byte[SEED_LENGTH]; @@ -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(); diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfReader.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfReader.java index 807549773..49ce9c287 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfReader.java +++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfReader.java @@ -1674,17 +1674,42 @@ private void readDecryptedDocObj() throws IOException { 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")); } @@ -1692,8 +1717,9 @@ private void readDecryptedDocObj() throws IOException { 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); diff --git a/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java b/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java index f9949ef87..e467add94 100644 --- a/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java +++ b/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java @@ -5,6 +5,7 @@ import java.io.ByteArrayOutputStream; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyPair; @@ -17,6 +18,9 @@ import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSEnvelopedData; +import org.bouncycastle.cms.KEMRecipientInformation; +import org.bouncycastle.cms.KeyTransRecipientInformation; +import org.bouncycastle.cms.RecipientInformation; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -36,6 +40,10 @@ class PdfPublicKeyEncryptionTest { private static X509Certificate recipient; private static KeyPair strangerKeys; private static X509Certificate stranger; + private static KeyPair kemKeys; + private static X509Certificate kemRecipient; + private static KeyPair kemStrangerKeys; + private static X509Certificate kemStranger; @BeforeAll static void createCertificates() throws Exception { @@ -43,15 +51,29 @@ static void createCertificates() throws Exception { recipient = selfSigned("CN=Recipient", BigInteger.ONE, recipientKeys); strangerKeys = KeyPairGenerator.getInstance("RSA").generateKeyPair(); stranger = selfSigned("CN=Stranger", BigInteger.TWO, strangerKeys); + // an ML-KEM key cannot sign, so its certificate is issued by the RSA key of the recipient + kemKeys = KeyPairGenerator.getInstance("ML-KEM-768").generateKeyPair(); + kemRecipient = issued("CN=Quantum Recipient", BigInteger.valueOf(3), kemKeys); + kemStrangerKeys = KeyPairGenerator.getInstance("ML-KEM-768").generateKeyPair(); + kemStranger = issued("CN=Quantum Stranger", BigInteger.valueOf(4), kemStrangerKeys); } private static X509Certificate selfSigned(String subject, BigInteger serial, KeyPair keys) throws Exception { - X500Name name = new X500Name(subject); + return certificate(subject, serial, keys, "CN=Recipient", keys); + } + + private static X509Certificate issued(String subject, BigInteger serial, KeyPair keys) throws Exception { + return certificate(subject, serial, keys, "CN=Recipient", recipientKeys); + } + + private static X509Certificate certificate(String subject, BigInteger serial, KeyPair keys, String issuer, + KeyPair issuerKeys) throws Exception { Date from = new Date(System.currentTimeMillis() - 86_400_000L); Date to = new Date(System.currentTimeMillis() + 86_400_000L); + X500Name issuerName = new X500Name(keys == issuerKeys ? subject : issuer); return new JcaX509CertificateConverter().getCertificate( - new JcaX509v3CertificateBuilder(name, serial, from, to, name, keys.getPublic()) - .build(new JcaContentSignerBuilder("SHA256withRSA").build(keys.getPrivate()))); + new JcaX509v3CertificateBuilder(issuerName, serial, from, to, new X500Name(subject), keys.getPublic()) + .build(new JcaContentSignerBuilder("SHA256withRSA").build(issuerKeys.getPrivate()))); } private static byte[] encryptFor(X509Certificate certificate, int encryptionType) throws Exception { @@ -103,4 +125,121 @@ void theDocumentKeyIsWrappedWithAes256() throws Exception { assertThat(envelope.getContentEncryptionAlgorithm().getAlgorithm()).isEqualTo(CMSAlgorithm.AES256_CBC); assertThat(envelope.getRecipientInfos().size()).isEqualTo(1); } + + @Test + void recipientCanReadAnAes256Document(@TempDir Path directory) throws Exception { + byte[] pdf = encryptFor(recipient, PdfWriter.ENCRYPTION_AES_256_V3); + Path file = Files.write(directory.resolve("aes256.pdf"), pdf); + + assertThat(readWith(file, recipient, recipientKeys)).contains(TEXT); + assertAesV3PublicKeyEncryption(pdf); + } + + @Test + void anotherCertificateCannotReadAnAes256Document(@TempDir Path directory) throws Exception { + Path file = Files.write(directory.resolve("other256.pdf"), + encryptFor(recipient, PdfWriter.ENCRYPTION_AES_256_V3)); + + assertThatThrownBy(() -> readWith(file, stranger, strangerKeys)).isInstanceOf(Exception.class); + } + + @Test + void mlKemRecipientCanReadAnAes256Document(@TempDir Path directory) throws Exception { + byte[] pdf = encryptFor(kemRecipient, PdfWriter.ENCRYPTION_AES_256_V3); + Path file = Files.write(directory.resolve("ml-kem.pdf"), pdf); + + assertThat(readWith(file, kemRecipient, kemKeys)).contains(TEXT); + assertAesV3PublicKeyEncryption(pdf); + } + + @Test + void mlKemRecipientCanReadAnAes128Document(@TempDir Path directory) throws Exception { + Path file = Files.write(directory.resolve("ml-kem-128.pdf"), + encryptFor(kemRecipient, PdfWriter.ENCRYPTION_AES_128)); + + assertThat(readWith(file, kemRecipient, kemKeys)).contains(TEXT); + } + + @Test + void anotherMlKemCertificateCannotReadTheDocument(@TempDir Path directory) throws Exception { + Path file = Files.write(directory.resolve("ml-kem-other.pdf"), + encryptFor(kemRecipient, PdfWriter.ENCRYPTION_AES_256_V3)); + + assertThatThrownBy(() -> readWith(file, kemStranger, kemStrangerKeys)).isInstanceOf(Exception.class); + } + + @Test + void rsaAndMlKemRecipientsCanBothReadTheDocument(@TempDir Path directory) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Document document = new Document(); + PdfWriter writer = PdfWriter.getInstance(document, out); + writer.setEncryption(new Certificate[]{recipient, kemRecipient}, + new int[]{PdfWriter.ALLOW_PRINTING, PdfWriter.ALLOW_PRINTING}, PdfWriter.ENCRYPTION_AES_256_V3); + document.open(); + document.add(new Paragraph(TEXT)); + document.close(); + Path file = Files.write(directory.resolve("both.pdf"), out.toByteArray()); + + assertThat(readWith(file, recipient, recipientKeys)).contains(TEXT); + assertThat(readWith(file, kemRecipient, kemKeys)).contains(TEXT); + } + + @Test + void stamperEncryptsAnExistingDocumentForAnMlKemRecipient(@TempDir Path directory) throws Exception { + ByteArrayOutputStream plain = new ByteArrayOutputStream(); + Document document = new Document(); + PdfWriter.getInstance(document, plain); + document.open(); + document.add(new Paragraph(TEXT)); + document.close(); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (PdfReader reader = new PdfReader(plain.toByteArray())) { + PdfStamper stamper = new PdfStamper(reader, out); + stamper.setEncryption(new Certificate[]{kemRecipient}, new int[]{PdfWriter.ALLOW_PRINTING}, + PdfWriter.ENCRYPTION_AES_256_V3); + stamper.close(); + } + Path file = Files.write(directory.resolve("stamped.pdf"), out.toByteArray()); + + assertThat(readWith(file, kemRecipient, kemKeys)).contains(TEXT); + } + + @Test + void theDocumentKeyIsEncapsulatedWithMlKem() throws Exception { + PdfPublicKeySecurityHandler handler = new PdfPublicKeySecurityHandler(); + handler.addRecipient(new PdfPublicKeyRecipient(kemRecipient, PdfWriter.ALLOW_PRINTING)); + + CMSEnvelopedData envelope = new CMSEnvelopedData(handler.getEncodedRecipient(0)); + RecipientInformation info = envelope.getRecipientInfos().getRecipients().iterator().next(); + + assertThat(info).isInstanceOf(KEMRecipientInformation.class); + assertThat(envelope.getContentEncryptionAlgorithm().getAlgorithm()).isEqualTo(CMSAlgorithm.AES256_CBC); + } + + @Test + void theDocumentKeyOfAnRsaRecipientIsStillTransported() throws Exception { + PdfPublicKeySecurityHandler handler = new PdfPublicKeySecurityHandler(); + handler.addRecipient(new PdfPublicKeyRecipient(recipient, PdfWriter.ALLOW_PRINTING)); + + CMSEnvelopedData envelope = new CMSEnvelopedData(handler.getEncodedRecipient(0)); + + assertThat(envelope.getRecipientInfos().getRecipients().iterator().next()) + .isInstanceOf(KeyTransRecipientInformation.class); + } + + @Test + void mlKemKeysAreRecognized() { + assertThat(PdfPublicKeySecurityHandler.isKemKey(kemKeys.getPublic())).isTrue(); + assertThat(PdfPublicKeySecurityHandler.isKemKey(recipientKeys.getPublic())).isFalse(); + } + + /** + * The encryption dictionary itself is not encrypted: it names the AES-256 crypt filter of ISO 32000-2. + */ + private static void assertAesV3PublicKeyEncryption(byte[] pdf) { + String raw = new String(pdf, StandardCharsets.ISO_8859_1); + assertThat(raw).contains("/Filter/Adobe.PubSec").contains("/SubFilter/adbe.pkcs7.s5").contains("/V 5") + .contains("/CFM/AESV3"); + } } From c7d0163428882c1a2e75d8ec5e002e702bbdde2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20R=C3=B8sdal?= Date: Thu, 3 Dec 2026 14:56:27 +0100 Subject: [PATCH 2/3] Reference PR #1815 in the changelog Co-Authored-By: Claude Opus 5.5 --- changelogs/4.0.1.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelogs/4.0.1.md b/changelogs/4.0.1.md index 45478f007..949958e81 100644 --- a/changelogs/4.0.1.md +++ b/changelogs/4.0.1.md @@ -8,7 +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.** 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. +* **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 From 0e2a1656bfecb7f2e6af303bbdf30c4b110c89a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20R=C3=B8sdal?= Date: Thu, 3 Dec 2026 15:01:08 +0100 Subject: [PATCH 3/3] Pass the issuer name instead of comparing key pairs by reference in the test Co-Authored-By: Claude Opus 5.5 --- .../org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java b/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java index e467add94..aa33ea60b 100644 --- a/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java +++ b/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfPublicKeyEncryptionTest.java @@ -59,7 +59,7 @@ static void createCertificates() throws Exception { } private static X509Certificate selfSigned(String subject, BigInteger serial, KeyPair keys) throws Exception { - return certificate(subject, serial, keys, "CN=Recipient", keys); + return certificate(subject, serial, keys, subject, keys); } private static X509Certificate issued(String subject, BigInteger serial, KeyPair keys) throws Exception { @@ -70,9 +70,8 @@ private static X509Certificate certificate(String subject, BigInteger serial, Ke KeyPair issuerKeys) throws Exception { Date from = new Date(System.currentTimeMillis() - 86_400_000L); Date to = new Date(System.currentTimeMillis() + 86_400_000L); - X500Name issuerName = new X500Name(keys == issuerKeys ? subject : issuer); return new JcaX509CertificateConverter().getCertificate( - new JcaX509v3CertificateBuilder(issuerName, serial, from, to, new X500Name(subject), keys.getPublic()) + new JcaX509v3CertificateBuilder(new X500Name(issuer), serial, from, to, new X500Name(subject), keys.getPublic()) .build(new JcaContentSignerBuilder("SHA256withRSA").build(issuerKeys.getPrivate()))); }