Run a freshly written ML-DSA-44 key generator against the official FIPS 204 known-answer vector and you can get a strange result: the opening 32 bytes of the public key match the reference exactly, and the packed t1 vector after them is wrong from start to finish. The lattice arithmetic is fine. One index byte in a SHAKE128 seed sits one position too late, and the only thing it corrupts is the matrix A, which the public key never stores
That mismatch opens a short list of FIPS 204 traps that produce keys which sign and verify against themselves yet agree with nobody else. This is an account of the ones we hit while porting ML-DSA-44, ML-DSA-65 and ML-DSA-87 to Object Pascal, the code shapes that avoid them, and how the finished primitives reach a PDF signature field in a Delphi application
ML-DSA in Delphi with a single dependency: SHAKE
PDFlibPas ships ML-DSA in the unit PDFlibMLDSA as nine ordinary functions: MLDSA44KeyGen, MLDSA44Sign and MLDSA44Verify, plus the same trio for 65 and 87. Keys, messages and signatures are plain AnsiString byte strings. KeyGen takes a 32-byte seed. Sign takes the expanded secret key, the message, a context string of at most 255 bytes and a 32-byte Rnd value, where all zeros selects the deterministic variant and fresh random bytes give the hedged one. There is no OpenSSL, no platform DLL and no C glue underneath
We think pure Pascal is the right call for this algorithm in particular, and the reason is the dependency graph. PDFlibPas builds with Delphi, C++Builder and FPC/Lazarus across Win32, Win64 and Unix targets, so binding a C post-quantum library would mean maintaining a native build for every one of those slots, plus the calling-convention and memory-ownership seams between them. ML-DSA needs no big-integer layer and no elliptic curve; its only primitive is SHAKE. The library already exposes a streaming XOF in PDFlibDigest: PLShakeXOFInit picks SHAKE128 (rate 168) or SHAKE256 (rate 136), followed by PLShakeXOFAbsorb, PLShakeXOFFinalize and as many PLShakeXOFSqueeze calls as the caller wants. Every rejection sampler in the ML-DSA unit is written against those four calls
Here is the main flow for ML-DSA-65, with the size checks we would put in any caller. The size constants are declared in the unit interface:
Uses
SysUtils, PDFlibMLDSA;
Procedure SignAndCheck(Const Seed, Doc: AnsiString);
Var
PublicKey, SecretKey, Rnd, Signature, Tampered: AnsiString;
Begin
// Seed is 32 bytes; guard it like the secret key it expands into
If not MLDSA65KeyGen(Seed, PublicKey, SecretKey) Then
Raise Exception.Create('ML-DSA-65 key generation failed');
// The Assert lines are checks we suggest you add yourself
Assert(Length(PublicKey)= MLDSA65_PUBLIC_KEY_BYTES); // 1952
Assert(Length(SecretKey)= MLDSA65_SECRET_KEY_BYTES); // 4032
Rnd:= StringOfChar(AnsiChar(#0), 32); // all zero: deterministic variant
If not MLDSA65Sign(SecretKey, Doc, 'invoice-v1', Rnd, Signature) Then
Raise Exception.Create('ML-DSA-65 signing failed');
Assert(Length(Signature)= MLDSA65_SIGNATURE_BYTES); // 3309
Assert(MLDSA65Verify(PublicKey, Doc, 'invoice-v1', Signature));
// Negative cases: wrong context, one flipped signature bit
Assert(not MLDSA65Verify(PublicKey, Doc, 'invoice-v2', Signature));
Tampered:= Signature;
Tampered[100]:= AnsiChar(Ord(Tampered[100])xor 1);
Assert(not MLDSA65Verify(PublicKey, Doc, 'invoice-v1', Tampered));
End;
All three parameter sets run through one shared engine. The set number selects a parameter table holding k and l, eta, tau, beta, gamma1, gamma2, omega and the challenge length, and the bit widths used for packing are computed from those values at run time. We chose computing over transcribing on purpose: a hand-copied bit width is the kind of constant that looks right in review and is off by one in production, and two of the traps below have exactly that shape. The declared sizes stay as named constants for validation: 1312, 2560 and 2420 bytes of public key, secret key and signature for ML-DSA-44, 1952, 4032 and 3309 for ML-DSA-65, and 2592, 4896 and 4627 for ML-DSA-87
Why does rho match while every t1 coefficient is wrong?
Because ExpandA, FIPS 204 Algorithm 32, is the one step that consumes rho without copying it into the output. The matrix A is sampled by seeding SHAKE128 with rho followed by two index bytes, column j and then row i, so the seed buffer is 34 bytes long. With 1-based AnsiString indexing those bytes belong in Msg[33] and Msg[34]. Our first draft wrote them to Msg[34] and Msg[35]. The public key starts with rho, so that prefix compared perfectly, while t = A·s1 + s2 came out wrong in every coefficient
Two more mistakes sat in the same routine. The absorb length has to be 34; absorbing 35 bytes feeds one stray byte into the sponge and changes the entire squeezed stream. The inner rejection loop also has to take every three-byte group a 168-byte SHAKE128 block can supply, including the one starting at offset 165, which works out to 56 groups per block. A cross-check script that stops at offset 162, written as range(0, 165, 3), drops the tail of every block and shifts the sampled t1 prefix from roughly the thirteenth byte onward, so compare against the official test vectors, not against a second implementation of your own
SetLength(Msg, 34);
Move(Rho[1], Msg[1], 32);
Msg[33]:= AnsiChar(J); // column index first
Msg[34]:= AnsiChar(I); // then the row index
PLShakeXOFInit(Ctx, True); // SHAKE128, rate 168
PLShakeXOFAbsorb(Ctx, @Msg[1], 34);
PLShakeXOFFinalize(Ctx);
Cnt:= 0;
While Cnt< N Do
Begin
PLShakeXOFSqueeze(Ctx, @Buf[0], 168);
BOff:= 0;
// BOff+2 <= 167 keeps the group at offset 165: 56 triples per block
While (BOff+ 2<= High(Buf))And (Cnt< N) Do
Begin
T3:= ((Buf[BOff+ 2]and $7F)shl 16)xor (Buf[BOff+ 1]shl 8)xor Buf[BOff];
If T3< Q Then
Begin
Poly^[Cnt]:= T3;
Inc(Cnt);
End;
Inc(BOff, 3);
End;
End;
With all three corrected, the SHA-256 digests of the complete ML-DSA-44 public and secret keys matched the official vectors. One debugging note deserves its own sentence, because it cost a full session. Python's hashlib.shake_128().digest(n) does not continue the stream on a second call; it returns the same prefix again. A block-by-block reference built that way re-consumes the very values the Pascal loop correctly rejected, so take the total length in one call and slice it into 168-byte blocks yourself
Sampling eta: ML-DSA-65 takes its own branch
FIPS 204 Algorithm 33 (ExpandS) defines two different nibble rules, and the PDFlibPas engine keeps two code paths to match. For eta = 2 a nibble is rejected at 15 and otherwise reduced mod 5. For eta = 4 the nibble is rejected at 9 or above and then used as-is, with no reduction at all. ML-DSA-44 and ML-DSA-87 both use eta = 2, so a port that starts from a working ML-DSA-44 build has every reason to reuse the mod 5 path. Do that for ML-DSA-65 and s1 and s2 are misaligned from coefficient zero. The resulting key pair is internally consistent, verifies its own signatures and matches no other implementation
Procedure StoreNibble(Nibble: Byte);
Var
M: Integer;
Centered: Cardinal;
Begin
If Cnt>= N Then
Exit;
If Eta= 4 Then
Begin
If Nibble>= 9 Then // reject, then take the nibble as-is
Exit;
M:= Nibble;
End
Else
Begin
If Nibble>= 15 Then // eta = 2: reject 15, then reduce mod 5
Exit;
M:= Nibble mod 5;
End;
If Eta>= M Then
Centered:= Eta- M
Else
Centered:= Q- (M- Eta); // coefficients live in [0, q)
Vec[I][Cnt]:= Centered;
Inc(Cnt);
End;
Both branches store eta minus the sampled value, folded into the canonical range [0, q) with q = 8380417, so an eta = 4 coefficient lands anywhere from −4 to +4 before folding
Let the sizes fail first: c-tilde and the gamma1 bit width
Two encoding parameters change with the security level in ways that are easy to miss when a working ML-DSA-44 build is sitting right there. The challenge hash c-tilde is 2λ/8 bytes long: 32 for ML-DSA-44, 48 for ML-DSA-65 and 64 for ML-DSA-87. Leave it at 32 and an ML-DSA-65 signature comes out at 3293 bytes instead of 3309, with the known-answer prefix diverging immediately
The second is the packing width of the mask vector z, which has to be the bit width of gamma1 itself rather than its exponent. For ML-DSA-65 and 87, gamma1 = 2^19, which takes 20 bits per coefficient. At 20 bits each z polynomial occupies 640 bytes; at 19 bits it occupies 608, and no conforming verifier will parse the result. The verifier side carries a matching trap, and we walked into that one too: a z decoding buffer sized at 192 bytes where ML-DSA-44 needs 576 (256 coefficients at 18 bits)
Our firm recommendation is to make signature length the first assertion in any ML-DSA test. It costs one line, it needs no reference implementation, and checking 2420, 3309 and 4627 against Length(Signature) catches most parameterisation mistakes before a single cryptographic comparison runs
How long can an ML-DSA signature take?
In principle there is no upper bound, because signing is rejection-based: it retries with an incremented counter kappa until a candidate passes its norm and hint checks. PDFlibPas caps that loop at 65535 attempts. When the budget runs out, MLDSA65Sign and its siblings return False with an empty signature instead of spinning inside a document-production thread. For scale, the official ML-DSA-44 vector succeeds at kappa = 4 with 55 hints against an omega ceiling of 80, so the cap is a guard rail and real signing never gets near it
The guard rail exists because we spent a while convinced signing had hung. Our suspicion landed on decompose and make_hint, FIPS 204 Algorithms 36 and 39, since that is where the numeric edge cases live. Both were correct. The real cause was an accumulation aimed at the wrong buffer: the vector feeding the hint computation must accumulate c·t0, while the original c·t0 has to survive untouched for the norm check. Point both at the same vector and the loop rejects every candidate forever with arithmetic that is correct line by line
On both the success path and the budget-exhausted path the unit zeroes the derived seeds, secret polynomials, masks, the challenge and the encoding buffers. The seed, secret key and Rnd you pass in remain yours to clear, since the library cannot know where those strings came from or who else holds a copy
Putting an ML-DSA signature into a PDF
TPDFlib.SetSignProcessMLDSAIdentity attaches an ML-DSA identity to a PDF signing process: a DER certificate whose key algorithm is id-ML-DSA-44, 65 or 87, plus the 32-byte seed, raw or wrapped in unencrypted PKCS #8 v2. The parameter set is read from the certificate, the public key is derived from the seed and compared with the certificate before anything is signed, and every signature draws a fresh 32-byte Rnd, so PDF signing always uses the hedged variant
Function SignWithMLDSA(PDF: TPDFlib; Const InFile, OutFile: WideString;
Const CertDER, SeedDER: AnsiString): Boolean;
Var
SP: Integer;
Begin
Result:= False;
SP:= PDF.NewSignProcessFromFile(InFile, '');
If SP= 0 Then
Exit;
Try
PDF.SetSignProcessField(SP, 'PQSignature');
If PDF.SetSignProcessMLDSAIdentity(SP, CertDER, SeedDER)= 1 Then
Begin
PDF.EndSignProcessToFile(SP, OutFile);
Result:= PDF.GetSignProcessResult(SP)= 1; // 1 = signed and written
End;
Finally
PDF.ReleaseSignProcess(SP);
End;
End;
Nothing about the signature dictionary changes. ISO 32000-2 §12.8 still governs it, and the SubFilter stays adbe.pkcs7.detached or ETSI.CAdES.detached; the post-quantum part lives entirely in the CMS SignerInfo, whose signatureAlgorithm carries the NIST OID 2.16.840.1.101.3.4.3.17, .18 or .19. Those arcs sit right next to .1, .2 and .3, which are DSA with SHA-224, SHA-256 and SHA-384. Check that OID against a verifier you did not write, because a signer and verifier in the same codebase read the same constant and will agree on a wrong one. Chain validation brings an environment snag: Windows CryptoAPI does not build chains for ML-DSA certificates, so TPDFlibSignatureVerifier validates those paths itself and accepts only anchors you register explicitly with AddTrustAnchorDER, never the Windows ROOT store
Hardware tokens go through TPDFlibPKCS11Client.SignMLDSA, a separate entry point because the PKCS #11 mechanism CKM_ML_DSA consumes the raw message instead of a precomputed digest, so SignHash and the external-digest callbacks cannot be reused. To find a key on a token without a certificate object, set CertificateOptional to True and supply PrivateKeyLabel or PrivateKeyID. At connect time the client reads CKA_PARAMETER_SET and accepts only CKP_ML_DSA_44, CKP_ML_DSA_65 and CKP_ML_DSA_87, so the default RSA and ECDSA certificate pairing is never loosened by accident
Where should ML-DSA go in production today? Our answer is a parallel track. Anything a third party must validate now should keep shipping as PAdES B-B through B-LTA signatures with timestamps and long-term validation data, because counterparties' validators decide what counts, and support for ML-DSA in signed PDFs is still uneven across them. Run ML-DSA keys and token wiring next to it on internal documents, where you control both ends. For local testing of the classical side, the self-signed certificate workflow built on CryptoAPI gives you an identity without a public CA, and the compliance and signing workbench that batches validation across a document corpus is a sensible place to run the size, vector and tamper checks above on every build
The ML-DSA unit is one piece of a larger native Object Pascal toolkit that also covers PAdES signing, encryption and PDF/A output. The PDFlibPas product page for Delphi, C++Builder and Lazarus lists the full component set and the supported compiler versions