Our first edwards448 base point was typed from memory. Key generation ran, signing ran, and every signature verified, yet no other Ed448 implementation on earth would have accepted a single one of them. Writing RFC 8032 Ed448 and the three RFC 5639 Brainpool ECDSA curves from scratch in Object Pascal turned up half a dozen traps, and most of them were of that kind: wrong code that stays perfectly consistent with itself
Field arithmetic is honest in one narrow sense: against a published test vector it matches byte for byte or it does not. You only learn which if you test against something outside your own code, because a broken signer and its matching broken verifier agree with each other all day
Why do Brainpool and Ed448 have to live inside a PDF library?
Both families arrive through document-signing profiles, and neither is available in the Pascal cryptographic libraries in common use, so a PDF library that wants them has to own them. Brainpool curves show up in European qualified-signature setups, and PDFlibPas implements brainpoolP256r1, brainpoolP384r1 and brainpoolP512r1 in its PDFlibBrainpool unit. Ed448 is part of the algorithm set ISO/TS 32002 brings to PDF, and its internal digest is SHAKE256 rather than anything from the SHA-2 family
That detail shaped one API decision. Inside the CMS signing profile SHAKE256 is legal only as Ed448's internal hash, so the PDFlibPas digest selector TPDFlibDigestAlgorithm deliberately has no SHAKE256 entry; offering one would let callers build combinations a conforming validator should reject
Why pure Pascal? A Delphi application that ships one binary with no crypto DLL has no provider to detect, no OpenSSL build to match and no behaviour that shifts when the host OS gets patched. Signing is the code path where we least want a moving dependency, so PDFlibEd448 and PDFlibBrainpool sit on nothing but the RTL
Domain constants come from the RFC text, and only from there
Every domain parameter in both units was copied from the specification text and cross-checked against vectors and libraries outside the Pascal code. A wrong generator crashes nothing; it yields a self-consistent signature system that disagrees with the rest of the world, and a sign-then-verify round trip in your own test suite passes every time
For edwards448 that meant the prime 2^448 − 2^224 − 1, the curve constant d = −39081, the group order and both decimal base-point coordinates taken from RFC 8032 §4.2, converted into the internal representation and checked against the first test vectors in RFC 8032 §7.4. For Brainpool the parameters came from RFC 5639, and an independent implementation generated known-answer vectors that were cross-verified against a system library in both directions before a line of Pascal existed
One shortcut looks universal and is not. On edwards25519 you can recover the base point from its fixed y value of 4/5; on edwards448 that value has no square root in the field. A short script disproved the idea in seconds
A mirror with unbounded integers before any Pascal
What made both units tractable was a second implementation in a language with arbitrary-precision integers, mimicking the Pascal one limb for limb. A limb here is one fixed-width digit of a big number: Ed448 field elements are 16 digits of 28 bits held in Int64 slots, and Brainpool values are 33 digits of 16 bits, a 528-bit working width that all three curves share
We built the mirror bottom-up. The arithmetic layer came alone at the start (multiply, subtract, carry propagation), stress-tested against algebraic invariants over 200 random inputs. Full key generation came after that, still inside the mirror, since that is where the semantic mistakes live and where they are cheap to find. The Pascal transcription came last
The payoff is diagnostic. Once the mirror passes every published vector, any disagreement with the Pascal side has to be a transcription slip, and printing the same intermediate value from both sides pins it down quickly. Without a mirror, one wrong digit inside a 448-bit scalar multiplication shows up only as a final signature that looks as random as a correct one
Carry handling is a good example. Our first carry routine added a bias before propagating so subtraction results stayed positive, and under large inputs it folded a spurious carry around 2^30 into the low digits. The shipped design uses floor division on every digit, so negative digits propagate correctly and subtraction needs no bias. The carry out of the top digit folds back through 2^448 ≡ 2^224 + 1 (mod p), landing on digits 0 and 8, with the loop capped at four rounds; we see two in practice. We prefer this over any bias scheme because it is far easier to reason about
Four places Ed448 goes quietly wrong
All four of these were located by probing intermediate values against the mirror, and every one produces output that looks valid
The sign of a term. Most published formulas for unified Edwards addition assume a = −1, while edwards448 has a = +1. Copy such a template and the numerator of the new y becomes a sum where it should be a difference. Patching the sign is the wrong fix. We re-derived the inversion-free product form from the affine addition law for an a = +1 curve, which leaves no room for a sign inherited from someone else's notation
One inverse too many. Recovering affine x from projective coordinates takes a single multiplication by the inverse of Z. Multiply by that inverse squared and you get a legal projective value and the wrong affine coordinate: correct y, wrong x. When one coordinate is right and the other is off, suspect normalisation before field arithmetic
Half a digest. The per-signature scalar and the challenge scalar must both be reduced modulo the group order from the complete 114-byte SHAKE256 output. Taking the first 57 bytes is a habit carried over by analogy, and the analogy is wrong anyway, since Ed25519 also reduces its full 64-byte SHA-512 output
Prefix order. Ed448 always hashes a domain-separation block, dom4, even in PureEdDSA mode with an empty context, where it is the 8 ASCII bytes SigEd448 plus a zero flag byte and a zero context length. RFC 8032 §5.2.6 puts it first: dom4 || prefix || M for the nonce, dom4 || R || A || M for the challenge. Put R and A ahead of it and your signatures verify against your own code and nothing else
Two Brainpool traps: buffer width and bit order
The Brainpool unit reused the Ed448 method, yet two mistakes still surfaced during the build, and neither looks like cryptography at first glance
The product buffer was too small. Two 33-digit values multiply into 66 digits, and the first draft declared the product array with 64. Writing past its end silently corrupted neighbouring variables; it showed up as wrong results and only became a crash once a wider diagnostic scan stepped on something important. The rule we kept: size fixed numeric buffers from the worst-case product width plus a margin. The public TBPProduct type in PDFlibBrainpool is 68 digits wide for that reason
The exponent was read in the wrong direction. Modular inversion uses Fermat's little theorem, a square-and-multiply loop with two correct shapes. The right-to-left form multiplies the accumulator, squares the base and must consume exponent bits from the least significant end. The left-to-right form squares the accumulator, multiplies, and walks from the most significant bit. Our draft paired a right-to-left body with a most-significant-first walk. Each half is textbook. Together they give a wrong inverse that looks like a plausible field element
A third hazard is structural. During scalar multiplication, Jacobian doubling and addition are called with the destination and a source as the same variable, so writing the new X before the old Y and Z have been read corrupts the later reads. Both point routines copy their inputs into locals on entry and compute only from those copies, which removes the whole class of aliasing bug at the cost of one record copy per call
How do you call the curves from Delphi?
For signing a PDF, use the sign-process API on TPDFlib and let it build the CMS container; the primitive units are there for tests, interop work and custom protocols. SetSignProcessBrainpoolIdentityFromFile takes a certificate whose key sits on one of the three Brainpool curves plus the matching private key, and the curve is read from the certificate. SetSignProcessEd448IdentityFromFile follows the same pattern for Ed448
uses
SysUtils, PDFlibrary;
function SignWithBrainpool(const InFile, OutFile, CertFile,
KeyFile: WideString): Integer;
var
PDF: TPDFlib;
SP: Integer;
begin
PDF := TPDFlib.Create;
try
SP := PDF.NewSignProcessFromFile(InFile, '');
if SP = 0 then
raise Exception.Create('Cannot open input PDF');
PDF.SetSignProcessField(SP, 'Signature1');
// Curve (P256r1 / P384r1 / P512r1) comes from the certificate
if PDF.SetSignProcessBrainpoolIdentityFromFile(SP, CertFile,
KeyFile) = 0 then
raise Exception.Create('Certificate or key file not readable');
PDF.EndSignProcessToFile(SP, OutFile);
Result := PDF.GetSignProcessResult(SP);
finally
PDF.Free;
end;
end;
With the primitives, the first test everyone writes is a round trip. It is necessary and nearly worthless alone, since a wrong base point or a misplaced dom4 passes it; add a tamper check and then compare against RFC 8032 §7.4 vectors taken from the RFC text. Ed448PublicKeyFromSeed and Ed448Sign want a 57-byte seed, public keys are 57 bytes and signatures 114, and other lengths return False. Ed448 here is PureEdDSA, so you pass the message itself (in a CMS signature, the DER-encoded signed attributes) rather than a precomputed hash
uses
PDFlibEd448;
// Your own test helper; the tamper check below is a suggested
// addition, not part of the library
function Ed448SelfCheck(const Seed, Msg: AnsiString): Boolean;
var
PublicKey, Signature, Tampered: AnsiString;
begin
Result := False;
if Length(Seed) <> 57 then
Exit;
if not Ed448PublicKeyFromSeed(Seed, PublicKey) then
Exit;
if not Ed448Sign(Msg, Seed, Signature) then
Exit;
// Round trip: proves consistency, not interoperability
if not Ed448Verify(Msg, PublicKey, Signature) then
Exit;
// One flipped bit in S must be rejected
Tampered := Signature;
Tampered[100] := AnsiChar(Byte(Tampered[100]) xor $01);
Result := not Ed448Verify(Msg, PublicKey, Tampered);
// Still to do: compare PublicKey and Signature with RFC 8032 §7.4
end;
The Brainpool primitives leave two jobs to the caller. BPSignFixedK takes the per-signature nonce K as a parameter instead of generating one, and we would design it the same way again: a repeated or predictable ECDSA nonce discloses the private key, so the source of randomness (OS CSPRNG, HSM, RFC 6979 derivation) belongs to the application and its compliance regime. The other job is the hash-to-integer step. ECDSA uses the leftmost bits of the digest trimmed to the bit length of the group order (SEC 1 §4.1.3), and BPSignFixedK and BPVerify expect E in that form. Pair SHA-256 with brainpoolP256r1, SHA-384 with P384r1 and SHA-512 with P512r1 and the trim is a no-op; mix them and you cut the digest yourself
uses
PDFlibBrainpool, PDFlibSecureRandom;
// Your own helper: digest trimming, nonce sampling and the
// point check are steps we suggest you add around the primitives
function BPSignAndCheck(const Digest, PrivD: AnsiString;
out RawSig: AnsiString): Boolean;
const
Size = 32; // brainpoolP256r1 scalar bytes
var
Curve: TBPCurve;
E, D, K, R, S, PubX, PubY: TBPValue;
NBytes, Rnd: AnsiString;
Attempt: Integer;
begin
Result := False;
RawSig := '';
Curve := BPLoadCurve(bpP256r1);
// Leftmost bytes only: a longer digest is cut to the order size
if not BPFromBytes(E, Copy(Digest, 1, Size)) then
Exit;
if not BPFromBytes(D, PrivD) then
Exit;
NBytes := BPToBytes(Curve.N, Size);
for Attempt := 1 to 16 do
begin
SetLength(Rnd, Size);
if not PLSecureRandomBytes(Rnd[1], Size) then
Exit; // no OS CSPRNG: refuse to sign
// Rejection sampling keeps K uniform in [1, n-1]
if (Rnd >= NBytes) or (Rnd = StringOfChar(#0, Size)) then
Continue;
if BPFromBytes(K, Rnd) and
BPSignFixedK(R, S, E, D, K, Curve) then
begin
RawSig := BPToBytes(R, Size) + BPToBytes(S, Size);
Break;
end;
end;
if RawSig = '' then
Exit;
// In a verifier PubX/PubY come from a certificate or a peer:
// check the point before verifying against it
Result := BPKeyGen(PubX, PubY, D, Curve) and
BPPointOnCurve(PubX, PubY, Curve) and
BPVerify(R, S, E, PubX, PubY, Curve);
end;
BPToBytes takes an explicit width, so r and s come out at the curve size with leading zeros kept, as a raw r || s layout requires; CMS uses the RFC 3279 Ecdsa-Sig-Value DER sequence instead, which the sign-process API builds for you. BPVerify works on the coordinates you hand it, so call BPPointOnCurve on any public key from a certificate or a peer. BPECDH runs that check on its own input point
Speed, and two habits that saved more time than any algorithm
Modular reduction in the Brainpool unit is bit-serial shift-and-subtract from the top set bit of the product, so each multiplication costs time roughly proportional to the bit width, and a brainpoolP256r1 verification lands on the order of a hundred milliseconds. Barrett reduction would be faster, but its precomputed constant needs 49 digits, more than the 33-digit working width, so it would mean widening every value or splitting the code per curve. For a handful of signatures per document we chose the simpler code
Incremental hot-fixing does not converge on a cryptographic unit. One Ed448 draft, patched again and again, ended up with 32 duplicated routines and a damaged structure before we rewrote it from the validated mirror. Write it once from a mirror you trust, or rewrite it
And check the executable timestamp before you believe a test result. During the Brainpool work an incremental MSBuild run compiled the units without relinking, so the tests kept running the previous binary and produced a full round of false leads about missing probe output. Clearing the DCU files was not enough; the project file had to be touched to force the relink
These curves share the signing and validation pipeline covered in PAdES signing and validation, and they sit next to the post-quantum work described in the FIPS 204 ML-DSA article. For local test certificates, see self-signed certificates with CryptoAPI. The complete list of signature algorithms, digests and container formats is on the losLab PDF Developer Library product page