Technical Article

Pure Pascal NIST Curve Arithmetic for PDF Signing

A P-384 key agreement routine can pass every P-256 test vector you feed it and still return a shared secret that is wrong in exactly one 64-bit limb, by exactly one. The cause is a single comparison in the final step of Montgomery multiplication, and P-256 never trips it because of where that prime keeps its only all-ones limb

Where curve arithmetic runs inside a PDF library

HotPDF runs elliptic-curve arithmetic in-process for one job: key agreement for public-key encrypted documents. When a recipient certificate carries an EC key, the ISO 32000-2 §7.6.5 recipient handler cannot wrap the document key with RSA; it has to agree on a shared secret with the recipient, derive a key-encryption key from it, and wrap the content key with the RFC 3394 AES key wrap. HotPDF supports five schemes for that, pkasECDHP256, pkasECDHP384, pkasECDHP521, pkasX25519 and pkasX448, and the derivation digest follows the curve: SHA-256 for P-256 and X25519, SHA-384 for P-384, SHA-512 for P-521 and X448

All five run as plain Object Pascal in the HPDFKeyAgreement unit. X25519 and X448 are Montgomery ladders written against RFC 7748; the three NIST prime curves use CIOS Montgomery multiplication over 64-bit limbs with Jacobian point arithmetic. The reason is environmental. The CNG raw-secret derivation is not available on every Windows build, its byte order has changed between Windows releases, and Free Pascal targets have no CNG at all. You can still see that history in envelopes produced elsewhere: when HotPDF unwraps a key-agreement recipient it tries the shared secret in both byte orders and lets the RFC 3394 integrity check decide which one the writer used

ECDSA signature verification is a different path. HPDFECDSAVerifyDigest hands the point arithmetic to Windows CNG through bcrypt.dll and returns evrProviderUnavailable when that provider cannot be loaded, so if signature validation on a non-Windows target matters to you, plan for that result code. The verification side is covered in the ECDSA and CMS verification walkthrough, and the pluggable signature-provider model explains how other algorithms plug in

Diagram of where HotPDF curve arithmetic is used: pure Pascal ECDH and X25519 or X448 key agreement for recipient-list encryption, with ECDSA signature verification handled through the Windows CNG provider
Key agreement for EC recipients runs in pure Pascal on all five curves, while ECDSA signature verification goes through the Windows CNG provider

From application code the whole stack is one call. HPDFComputeKeyAgreementSecret takes a curve OID, your private scalar and the peer public key, and reports problems through an Issue string instead of raising:

uses
  System.SysUtils, HPDFKeyAgreement;

function AgreeP384(const MyScalar, PeerPoint: TBytes): TBytes;
var
  Issue: string;
begin
  // MyScalar: 48-byte big-endian d
  // PeerPoint: 97-byte uncompressed 04 || X || Y
  // OwnPublicPoint is ignored on the NIST curves, so nil is fine here
  if not HPDFComputeKeyAgreementSecret(HPDFOIDECP384, MyScalar, nil,
    PeerPoint, Result, Issue) then
    raise Exception.Create('P-384 agreement refused: ' + Issue);
  // Result is the 48-byte big-endian x-coordinate of d * PeerPoint
end;

Wrong lengths come back as "NIST curve key material lengths do not match the curve". A peer point that fails y^2 = x^3 - 3x + b comes back as "peer public point is not on the curve" before any scalar multiplication starts, and a zero scalar or a result at infinity is refused the same way. For the full encryption workflow built on top of this, see certificate recipients with ECDH in Delphi

CIOS and the subtraction at the end

Montgomery multiplication avoids division by working in a transformed domain where reduction becomes a shift. CIOS, Coarsely Integrated Operand Scanning, interleaves multiply and reduce limb by limb, so the accumulator never grows beyond the modulus width plus a small carry. The inner loops are regular and easy to check against a reference. The tail is where things go wrong: after the last pass the accumulator T can be anywhere below 2p, and the routine has to subtract p once if and only if T >= p

That tail has two parts. A comparison decides whether to subtract, walking from the most significant limb down. Then the subtraction itself runs from the least significant limb up, carrying a borrow. Both parts have a trap

The comparison first. T has one more limb than the modulus, T[L], and it can be non-zero: for P-256 and P-384, 2p is larger than 2^256 and 2^384 respectively, so a value between p and 2p can spill a bit past the limb window. Compare only the low L limbs and that value looks small, the subtraction is skipped, and the result is off by exactly p. HotPDF treats a non-zero T[L] as "subtract" before it looks at any other limb

Why does adding the borrow break P-384 but not P-256?

The natural way to write the borrow test in the subtraction loop is "does this limb need a borrow if I subtract P[I] plus the incoming borrow?", which reads as T[I] < P[I] + Borrow. Unsigned 64-bit arithmetic turns that into a trap. When P[I] is $FFFFFFFFFFFFFFFF and Borrow is 1, the sum wraps to zero, the test asks whether T[I] is below zero, and the answer is always no. The borrow is dropped, and the next limb up stays one too large

// Final conditional subtraction, limb 0 upward (your own field code)

// Wrong: P[I] + Borrow wraps to zero when P[I] = $FFFFFFFFFFFFFFFF,
// so an all-ones limb never passes a borrow upward
NeedBorrow := Ord(T[I] < P[I] + Borrow);

// Correct: never add to a limb before comparing
NeedBorrow := Ord((T[I] < P[I]) or ((T[I] = P[I]) and (Borrow = 1)));
T[I] := T[I] - P[I] - Borrow;   // relies on wraparound, see below
Borrow := NeedBorrow;

// And the decision to subtract at all must look at the spill limb first
if (T[L] <> 0) or not LowLimbsBelowModulus(T, P, L) then  // your helper
  SubtractModulus(T, P, L);                                 // your helper

Look at where each prime keeps its all-ones limbs, numbering from limb 0 at the low end. P-256 has exactly one, limb 0, and limb 0 is the one place where the incoming borrow is always zero. Its upper limbs are $00000000FFFFFFFF, 0 and $FFFFFFFF00000001, so the wrong expression never wraps and agrees with the correct one on every input. P-384's top three limbs are all ones. P-521 has eight of them, limbs 0 through 7

Montgomery reduction borrow wrap diagram contrasting the wrong limb comparison with correct borrow propagation in P-384 arithmetic
Adding the borrow to an all-ones limb wraps to zero, so P-384 and P-521 lose the borrow while P-256, whose only all-ones limb is the lowest, hides the error

The result is about as unfriendly to a test suite as a bug gets. The most-tested curve is immune. The others fail only when the subtraction runs and a borrow reaches an all-ones limb, which depends on operand values, so a handful of P-384 vectors can pass by luck. In an encryption workflow the symptom is a recipient who cannot open a file that was written without complaint. Our position for anyone porting this kind of code: until a curve matches independent reference vectors, make it return an "unavailable" status. A refused curve costs you a support ticket; a curve that quietly computes the wrong secret costs you documents nobody can open

Delphi adds one wrinkle of its own. The correct subtraction line relies on unsigned wraparound, and with overflow checking enabled ({$Q+}, common in debug configurations) a wrapping UInt64 add or subtract raises EIntOverflow instead. HotPDF's limb helpers split each 64-bit add and subtract into 32-bit halves so the modular result is the same whichever way the project is compiled. If you write your own field code, either do the same or pin {$Q-} locally around it, because a routine that behaves differently in Debug and Release is the last thing you want to be bisecting. Free Pascal has a further restriction on 32-bit targets: it rejects UInt64 as a for loop variable, so limb indices belong in Integer

Locating a one-limb, off-by-one error

If a port shows this symptom, reading the code rarely finds it. The CIOS loops look right, the constants look right, and P-256 works, which pulls attention everywhere except the tail. A mechanical sequence does better, and it carries over to any field-arithmetic port

Start by ruling out the constants: regenerate every limb of p, R and R^2 in a language with unbounded integers and compare limb by limb. If they match, instrument the arithmetic rather than the public API. A temporary dump that prints the Montgomery product of the R^2 constant, then x^3 and y^2 for a known point, lets you compare each value with the same quantity computed independently. Suppose the x chain comes out correct end to end while y^2 differs in one limb, by one

A difference of exactly one in exactly one limb rules out a multiplication error, which scrambles many limbs, and a constant error, which would show up in the x chain too. It is the signature of a borrow chain, and the only borrow chain in the routine is the final conditional subtraction. Before trusting that reading, verify the reference values themselves. A byte-swapped reference value, say one written in little-endian order where the dump prints big-endian limbs, produces a second mismatch that looks like a second bug. Check the byte order of your ground truth before you let it accuse your code

Flow chart of how a curve arithmetic error is located by regenerating constants, dumping Montgomery intermediates and diffing against mirror truth
A one-limb difference of exactly one points straight at the only borrow chain in the routine, and a byte-swapped reference value can fake a second error

Curve constants must be derived, never typed

The P-521 prime is 2^521 - 1, which written in hex is a leading 1 followed by 130 F digits, 131 digits in all. A transcription that comes up a few Fs short still parses, and if R and R^2 are then computed from that short prime, the three constants agree with each other perfectly while all of them are wrong. Self-consistency proves nothing about correctness here. The robust procedure is to compute R = 2^(64*L) mod p from the prime you actually load, then check R * R mod p against your R^2 constant

P-521 makes a good sanity check because its numbers are small enough to verify by eye. With nine limbs, R = 2^576 mod (2^521 - 1) = 2^55, which is $80000000000000, and R^2 = 2^110. The per-curve Montgomery factor -p^-1 mod 2^64 is just as easy to reason about: P-256 and P-521 both have an all-ones lowest limb, so p is congruent to -1 modulo 2^64 and the factor is 1, while P-384's lowest limb is $00000000FFFFFFFF and its factor is $100000001

A generic multi-limb subtraction has the same wrap hazard as the conditional subtraction. If you compute Y[I] + Borrow first and Y[I] is all ones, the sum wraps to zero; the correct response is to leave X[I] unchanged and carry the borrow into the next limb, not to clear it. On primes whose upper limbs are all ones, clearing it is a systematic error rather than an occasional one

Testing all five curves from Delphi

For Montgomery-ladder code, the fastest debugging tool turned out to be a mirror: transcribe the Pascal control flow line by line into a language with big integers, run both, and probe the same intermediate in each until they diverge. When the mirror is right and the Pascal is wrong, the difference is a transcription slip, and the probe finds it in seconds. The three classic RFC 7748 ladder mistakes all show up this way: a constant-time swap whose second line reuses the value the first line already swapped, a final step that returns z^-1 without multiplying it into x, and a small-constant multiply that assembles half-word products with or and drops the carry out of the low half

From the application side, a known-answer test through the public entry point is the check that matters. RFC 7748 §5.2 publishes X25519 and X448 vectors as little-endian byte strings; for the NIST curves, generate a key pair with any independent tool, export the keys in DER, and slice the scalar and point bytes out at known offsets. Do not pull hex out of a text dump with a regular expression. A pattern that swallows one character produces a vector that is one byte off, and a correct implementation then fails a test it should pass:

uses
  System.SysUtils, System.IOUtils, HPDFCrypt, HPDFKeyAgreement;

procedure CheckVector(const CurveOID: AnsiString; const Dir: string);
var
  Scalar, Peer, Expected, Secret: TBytes;
  Issue: string;
begin
  Scalar   := TFile.ReadAllBytes(TPath.Combine(Dir, 'scalar.bin'));
  Peer     := TFile.ReadAllBytes(TPath.Combine(Dir, 'peer.bin'));
  Expected := TFile.ReadAllBytes(TPath.Combine(Dir, 'shared.bin'));
  if not HPDFComputeKeyAgreementSecret(CurveOID, Scalar, nil, Peer,
    Secret, Issue) then
    raise Exception.CreateFmt('%s refused: %s', [string(CurveOID), Issue]);
  if (Length(Secret) <> Length(Expected)) or
    not CompareMem(@Secret[0], @Expected[0], Length(Secret)) then
    raise Exception.CreateFmt('%s: shared secret mismatch', [string(CurveOID)]);
end;

procedure CheckAllCurves;
var
  A, B, PubA, PubB, S1, S2: TBytes;
begin
  CheckVector(HPDFOIDECP256, 'vectors\p256');
  CheckVector(HPDFOIDECP384, 'vectors\p384');   // the curve to watch
  CheckVector(HPDFOIDECP521, 'vectors\p521');
  CheckVector(HPDFOIDX25519, 'vectors\x25519');
  CheckVector(HPDFOIDX448,   'vectors\x448');

  // Round trip with fresh scalars: catches asymmetric slips only
  SetLength(A, 32);
  SetLength(B, 32);
  AESGenerateRandomBytes(@A[0], 32);
  AESGenerateRandomBytes(@B[0], 32);
  PubA := HPDFX25519PublicFromScalar(A);
  PubB := HPDFX25519PublicFromScalar(B);
  S1 := HPDFX25519(A, PubB);
  S2 := HPDFX25519(B, PubA);
  if not CompareMem(@S1[0], @S2[0], 32) then
    raise Exception.Create('X25519 round trip disagrees');
  HPDFSecureClearBytes(A);
  HPDFSecureClearBytes(B);
end;

Run the known-answer half against vectors that hit the borrow path. For P-384 that means several key pairs, not one, since a single vector can skip the subtraction entirely. The round trip at the end is cheap and runs on every build, but it only proves the two sides agree with each other; a wrong constant shared by both sides passes it every time, which is why the fixed vectors come first

If you are wiring EC recipients into document encryption or choosing curves for a signing profile, the PAdES signing walkthrough covers the signing side. Licensing, editions and the full algorithm list are on the HotPDF Delphi PDF component page