Skip to content
GDKsoftwarePublic

About

Signature verification in pure Delphi: ECDSA P-256, RSA PKCS#1 v1.5, Ed25519 and X.509 certificates

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Crypto4D

Crypto4D verifies digital signatures, encrypts data with AES-GCM and hashes passwords, in pure Delphi. The same source compiles for Win32, Win64 and Linux64 and needs no DLL or shared library next to your program.

For signatures it only verifies: there is no signing and no generation of key pairs, so the library never handles a private key.

Encryption and password hashing work with secrets. That code is written to run in constant time, but no measurement backs this; Secrets and side channels says what the code does to protect secrets and what it does not.

This library has not been audited by an external party. Read the section on testing below and decide for yourself whether that is enough for your use.

Supported algorithms

Algorithm Class Notes
ECDSA on P-256 with SHA-256 (ES256) TEcdsaP256 Signature as ASN.1 DER or as raw r || s (64 bytes)
RSA PKCS#1 v1.5 with SHA-256 (RS256) TRsaPkcs1Sha256 Odd modulus from 2048 up to 8192 bits, odd exponent from 3 up to 2^33 - 1
Ed25519 (RFC 8032) TEd25519 Strict variant, see below
X.509 certificates TX509CertificateInfo Parsing, and checking the signature with a given issuer key
AES-256-GCM with a random nonce TAes256GcmEncryption Authenticated encryption of bytes and strings; picks the nonce for you
AES-256-GCM with a password TPasswordEncryption The key comes from Argon2id; parameters, salt and a key commitment are stored in the message
AES-GCM (NIST SP 800-38D) TAesGcm Keys of 128, 192 and 256 bits, a nonce of 96 bits that you supply, a tag of 128 bits
Password hashing TPasswordHash Argon2id by default, bcrypt and PBKDF2-HMAC-SHA-256 on request; one string per hash
Argon2 (RFC 9106) TArgon2 Argon2id, Argon2i and Argon2d, version 1.3, bytes in and bytes out
bcrypt TBcrypt Cost from 4 up to 31, bytes in and bytes out
PBKDF2-HMAC-SHA-256 (RFC 8018) TPbkdf2HmacSha256 Bytes in and bytes out

Every class lives in the unit of the same name: TAes256GcmEncryption in Crypto4D.Aes256GcmEncryption, TPasswordEncryption in Crypto4D.PasswordEncryption, TPasswordHash in Crypto4D.PasswordHash. The supporting types:

Type Unit What it is
TBigInteger Crypto4D.BigInteger Non-negative integers of any size
TDerReader Crypto4D.Der A strict DER reader
TCryptoRandom Crypto4D.Random Random bytes from the operating system
TBlake2b Crypto4D.Blake2b BLAKE2b without a key
TAesBlockCipher Crypto4D.Aes The AES block cipher, encryption direction only
TByteArrays Crypto4D.Bytes Comparing and wiping byte arrays
TArgon2Variant Crypto4D.Argon2.Variant Argon2id, Argon2i or Argon2d
TArgon2Parameters Crypto4D.Argon2.Parameters Memory, passes and lanes of Argon2
TPasswordHashLimits Crypto4D.PasswordHash.Limits The cost a stored hash or a message may ask for
TPasswordVerificationOutcome Crypto4D.PasswordHash.VerificationOutcome Why a password does not match
TPasswordDecryptionOutcome Crypto4D.PasswordEncryption.DecryptionOutcome Why a message does not decrypt

There is no AES-CBC and no AES-CTR. Both encrypt without authenticating, so an attacker can change a ciphertext unnoticed: padding oracle attacks on CBC and bit flipping attacks on CTR depend on that. Use TAes256GcmEncryption.

Requirements

Written for Delphi 11 and later, tested on Delphi 13.

Add the src folder to the search path of your project, or build the runtime package packages\Crypto4D.dproj.

Return values and exceptions

A verification function returns False when the signature does not verify. That includes every kind of bad input from outside: a damaged signature, a signature of the wrong length, a public key that is not on the curve, a certificate that does not parse.

ECrypto4DArgumentError is raised only when the caller passes something a function can never work with:

  • a P-256 public key whose coordinates are not 32 bytes each
  • an Ed25519 public key that is not 32 bytes
  • an RSA modulus that is even, under 2048 bits or over 8192 bits
  • an RSA public exponent that is even, smaller than 3, or 2^33 or larger
  • an AES key that is not 16, 24 or 32 bytes (TAesGcm) or not 32 bytes (TAes256GcmEncryption), or a nonce that is not 12 bytes
  • a plaintext of more than 2^36 - 32 bytes
  • Argon2, bcrypt or PBKDF2 parameters outside the limits of the algorithm, Argon2 memory that does not fit in the address space of the program, and for HashBcrypt a password of more than 72 bytes or with the character #0
  • Argon2id parameters below the minimum for messages when you encrypt with a password (see Limits)

Decrypting and verifying a password follow the same rule as verifying a signature. TryDecrypt, TryDecryptString, TryOpen and TPasswordHash.Verify return False for a message that was changed, a wrong key, a wrong password, a stored hash that is damaged or not supported, and a hash or a message whose cost is outside the limits (see Limits). The message of an exception never holds a key, a password or plaintext.

ECrypto4DRandomError is raised when the operating system cannot deliver random bytes for a key, a nonce or a salt. ECrypto4DStateError is raised when an object is used in a state it cannot work in, such as an AES cipher after Wipe.

Argon2 allocates the memory that its parameters ask for, up to 1 GiB within the limits for stored hashes. When the operating system cannot deliver it, the RTL raises EOutOfMemory. That is the one exception that does not descend from ECrypto4DError; the documentation of each routine that runs Argon2 names it.

When the key comes from outside, check it before you construct it:

  • RSA: TRsaPublicKey.IsSupportedModulus and TRsaPublicKey.IsSupportedExponent
  • P-256: both coordinates are 32 bytes, or TEcdsaP256PublicKey.IsUncompressedPoint for the 65 byte form
  • Ed25519: the key is 32 bytes (TEd25519.PublicKeySize)
  • a key from a certificate or a SubjectPublicKeyInfo: TryGetEcdsaP256Key, TryGetRsaKey and TryGetEd25519Key do these checks and return False

A P-256 key of the right length that is not a point on the curve does not raise. The verification returns False for it.

TBigInteger raises ECrypto4DArithmeticError for a division by zero, a subtraction with a negative result and a modular inverse that does not exist. All exceptions of Crypto4D descend from ECrypto4DError.

Usage

ECDSA P-256 with SHA-256

uses
  Crypto4D.Ecdsa;

function IsSignedByKey(const X, Y, Message, DerSignature: TBytes): Boolean;
begin
  const Key = TEcdsaP256PublicKey.FromCoordinates(X, Y);
  Result := TEcdsaP256.VerifyDer(Key, Message, DerSignature);
end;

TEcdsaP256PublicKey.FromUncompressedPoint takes the 65 byte form 04 || X || Y. TEcdsaP256.VerifyRaw takes the signature as 64 bytes r || s.

The public key must be a point on the curve, and r and s must be in the range from 1 up to and including n - 1. A DER signature must be strict DER: a non-minimal length or integer encoding is rejected. A signature with a high s value is accepted; there is no low-S rule.

RSA PKCS#1 v1.5 with SHA-256

uses
  Crypto4D.Rsa;

function IsSignedByKey(const Modulus, Exponent, Message, Signature: TBytes): Boolean;
begin
  const Key = TRsaPublicKey.Create(Modulus, Exponent);
  Result := TRsaPkcs1Sha256.Verify(Key, Message, Signature);
end;

Modulus and exponent are big-endian byte arrays. The signature must be exactly as long as the modulus. Crypto4D builds the one encoded message that is valid for the given message and compares it byte for byte with the decrypted signature; it does not parse the padding. A DigestInfo without the NULL parameter is therefore rejected.

The modulus and the exponent have an upper limit because the other party picks the key, and the time one verification takes grows with the size of the modulus and of the exponent.

Ed25519

uses
  Crypto4D.Ed25519;

function IsSignedByKey(const PublicKey, Message, Signature: TBytes): Boolean;
begin
  Result := TEd25519.Verify(PublicKey, Message, Signature);
end;

The verification is strict:

  • S must be smaller than the group order L
  • a public key or R in a non-canonical encoding is rejected
  • a public key of small order is rejected
  • the equation [S]B = R + [k]A is checked as it stands, without multiplying by the cofactor 8

Strict does not mean that the public key must lie in the prime-order subgroup: a key with a torsion component that is not of small order (a mixed-order key) is accepted, and its signatures verify when they satisfy the equation as it stands.

Only the public key is checked for small order. R is not: a signature whose R is one of the eight points of small order is accepted when the equation holds. Case 2 of ed25519-speccheck is such a signature.

Other libraries draw the line elsewhere. The README of the C2SP CCTV Ed25519 vectors lists their behaviour:

  • Go, OpenSSL and verify of ed25519-dalek accept a public key of small order and a public key in a non-canonical encoding. Crypto4D rejects both.
  • verify_strict of ed25519-dalek rejects an R of small order. Crypto4D accepts it.
  • A ZIP 215 verifier accepts non-canonical encodings and multiplies by the cofactor. Crypto4D does neither.

X.509 certificates

uses
  Crypto4D.X509;

function IsIssuedBy(const CertificateDer, IssuerDer: TBytes): Boolean;
begin
  var Certificate: TX509CertificateInfo;
  var Issuer: TX509CertificateInfo;
  const BothParse = TX509CertificateInfo.TryParse(CertificateDer, Certificate) and
                    TX509CertificateInfo.TryParse(IssuerDer, Issuer);
  if not BothParse then
    Exit(False);

  Result := Certificate.IsSignedBy(Issuer.PublicKey);
end;

A parsed certificate gives access to the bytes of tbsCertificate, the serial number, issuer, validity and subject as DER, the subject public key with its algorithm, both signature algorithm identifiers, the signature and the extensions as raw values (TryFindExtension). TX509PublicKeyInfo converts the public key to the key types above with TryGetEcdsaP256Key, TryGetRsaKey and TryGetEd25519Key.

IsSignedBy supports ecdsa-with-SHA256 with a P-256 key, sha256WithRSAEncryption and Ed25519.

The parameters of the signature AlgorithmIdentifier may be absent or an ASN.1 NULL for ecdsa-with-SHA256 and sha256WithRSAEncryption, and must be absent for Ed25519. RFC 5758 says they must be absent for ECDSA, but certificates with a NULL are in use, among them attestation root certificates in the FIDO Metadata Service, and OpenSSL accepts them. The identifier inside tbsCertificate and the one outside it must be equal, parameters included, and any other parameter is rejected.

TryParse reads the structure of a certificate as strict DER. It also rejects a certificate that states version 1 explicitly, has a serial number that is not in its shortest encoding, holds a unique identifier in version 1 or extensions below version 3, or names an extension twice.

TryParse checks the structure, not the meaning. Issuer, validity and subject only have to be a SEQUENCE and are kept as DER. The value of an extension is not read. The parameters of an algorithm that Crypto4D does not know can be any single DER element.

Crypto4D does not validate a certificate chain. It has no trust store and it does not look at validity dates, key usage, name constraints or revocation. IsSignedBy answers one question: was this certificate signed with that key.

Encrypting with AES-256-GCM

uses
  Crypto4D.Aes256GcmEncryption;

procedure StoreSecretNote(const Key: TBytes; const Note: string);
begin
  const Encrypted = TAes256GcmEncryption.EncryptString(Key, Note);
  SaveToDatabase(Encrypted);
end;

function TryLoadSecretNote(const Key: TBytes; out Note: string): Boolean;
begin
  const Encrypted = LoadFromDatabase;
  Result := TAes256GcmEncryption.TryDecryptString(Key, Encrypted, Note);
end;

TAes256GcmEncryption.GenerateKey returns a new key of 32 random bytes. Keep the key outside the data it protects, for example in a key vault or in a file that only the service account can read.

Encrypt and TryDecrypt do the same for TBytes. An encrypted message is the 12 byte nonce, the ciphertext and the 16 byte tag in one array, 28 bytes longer than the plaintext. EncryptString encrypts the UTF-8 bytes of the text and returns that array as Base64 without line breaks. Other libraries can read the format: split off the first 12 bytes as nonce and the last 16 bytes as tag.

Every message gets a fresh random nonce, so encrypting the same text twice gives two different results. TryDecrypt returns False when even one bit of the message was changed, or when the key is wrong. TryDecryptString also returns False for text that is not Base64 exactly as EncryptString writes it, and for a message that does not decrypt to UTF-8.

A password is not a key. To encrypt with a password, use TPasswordEncryption, described in the next section.

The optional last parameter AssociatedData binds a message to its context without storing that context in the message. Pass the id of the record a value belongs to, and a value that is copied to another record does not decrypt there. Decrypting needs the same bytes.

Limits:

  • One key should encrypt no more than 2^32 messages, the bound of NIST SP 800-38D for random nonces. Change the key before that.
  • A message is encrypted in memory as a whole. There is no streaming interface for large files.
  • A message is at most 2^36 - 32 bytes.

Encrypting with a password

uses
  Crypto4D.PasswordEncryption;

const Encrypted = TPasswordEncryption.EncryptString(Password, Note);

var Opened: string;
const IsAuthentic = TPasswordEncryption.TryDecryptString(Password, Encrypted, Opened);

TPasswordEncryption.Encrypt derives a key from the password with Argon2id under a fresh random salt and encrypts with AES-256-GCM under a fresh random nonce. The message carries everything that decrypting needs besides the password: the version of the format, the Argon2id parameters, the salt, a commitment to the key and the nonce. It is 89 bytes longer than the plaintext (TPasswordEncryption.Overhead). EncryptString encrypts the UTF-8 bytes of a text and returns the message as Base64 without line breaks; TryDecrypt and TryDecryptString reverse the two. All four take optional associated data as their last parameter.

Without parameters the key comes from TArgon2Parameters.Recommended (19 MiB, 2 passes, 1 lane), the same cost as TPasswordHash.Hash. The overloads with a TArgon2Parameters take your own, but no less than 19 MiB and 2 passes; lower parameters raise ECrypto4DArgumentError. Decrypting checks the parameters against TPasswordHashLimits.ForMessages before Argon2id runs, so a message from outside cannot make your program spend more memory or time than those limits allow, and cannot ask for a cost so low that guessing the password is cheap (see Limits). A message made with parameters above these limits needs the overload with limits of your own.

The overloads with an out parameter of type TPasswordDecryptionOutcome take limits and tell why a message does not decrypt:

Outcome Meaning
Decrypted The message is authentic and was decrypted
Failed The password is wrong, or the message or its associated data was changed; the two cannot be told apart
OutsideLimits The Argon2id parameters are above a maximum or below a minimum of the limits; nothing was computed
UnsupportedVersion The first byte names a version of the format that Crypto4D does not read
Malformed Too short, not Base64 as EncryptString writes it, parameters outside the limits of RFC 9106, or a text that is not UTF-8
var Opened: string;
var Outcome: TPasswordDecryptionOutcome;
const Limits = TPasswordHashLimits.ForMessages;
if not TPasswordEncryption.TryDecryptString(Password, Encrypted, Limits, Opened, Outcome) then
  ReportUnreadableNote(Outcome);

The format, version 1, with all numbers big-endian:

Offset Size Field
0 1 Version, 01
1 4 Argon2id memory in KiB (m)
5 4 Argon2id passes (t)
9 4 Argon2id lanes (p)
13 16 Salt
29 32 Key commitment
61 12 Nonce
73 n Ciphertext, as long as the plaintext
73 + n 16 Tag

Argon2id version 19 of the UTF-8 bytes of the password and the salt, without a secret value or associated data of its own, gives 64 bytes. The first 32 are the AES-256 key; the last 32 are the key commitment and are stored in the message. The associated data of AES-GCM is the header (bytes 0 up to 60) followed by the associated data of the caller, so a changed header does not decrypt. TryDecrypt returns Malformed for a message shorter than 89 bytes and UnsupportedVersion for any version other than 1. A later version of the format can change everything after the first byte. No other tool reads this format; the idea of a work factor and a salt that travel with the message comes from the scrypt recipient of age.

The key commitment is there because AES-GCM does not commit to its key. An attacker who derives the keys of many candidate passwords can build one ciphertext whose tag is valid under all of them. A server that tells whether such a message decrypts then answers for all those passwords at once: the partitioning oracle attack of Len, Grubbs and Ristenpart (USENIX Security 2021). age avoids it in its scrypt recipient by limiting the length of the wrapped key; a message here has no such limit. Crypto4D follows the generic fix of Albertini et al. (USENIX Security 2022): one derivation gives both the encryption key and a commitment, and the commitment travels with the ciphertext. Decrypting compares the commitment, without stopping at the first difference, before AES-GCM runs, so a message decrypts under one password only. Storing the commitment itself instead of a hash of it gives nothing away: whoever holds the message can already test a guessed password against the tag, at the same cost of one Argon2id run.

AES-GCM with your own nonce

uses
  Crypto4D.AesGcm;

const Sealed = TAesGcm.Seal(Key, Nonce, Plaintext, AssociatedData);

var Opened: TBytes;
const IsAuthentic = TAesGcm.TryOpen(Key, Nonce, Sealed, AssociatedData, Opened);

TAesGcm is for a protocol that prescribes the nonce, or for data from another system. The key is 16, 24 or 32 bytes and the nonce 12 bytes. Seal returns the ciphertext followed by the 16 byte tag, the layout that Go, Java, WebCrypto and the Python package cryptography use. Other nonce and tag lengths are not supported.

A nonce must never be used twice with the same key. Two messages under one key and nonce reveal the XOR of their plaintexts and let an attacker forge messages.

Password hashing

uses
  Crypto4D.PasswordHash;

procedure Register(const UserName, Password: string);
begin
  const StoredHash = TPasswordHash.Hash(Password);
  SaveUser(UserName, StoredHash);
end;

function Login(const UserName, Password: string): Boolean;
begin
  const StoredHash = LoadHashOfUser(UserName);
  Result := TPasswordHash.Verify(Password, StoredHash);

  if Result and TPasswordHash.NeedsRehash(StoredHash) then
    SaveUser(UserName, TPasswordHash.Hash(Password));
end;

Hash returns one line of text of 97 characters that names the algorithm, its cost and the random salt. Store that string; Verify needs nothing else.

Function Algorithm and default cost Result
Hash Argon2id, 19 MiB of memory, 2 passes, 1 lane $argon2id$v=19$m=19456,t=2,p=1$salt$hash
HashArgon2id Argon2id with your TArgon2Parameters the same form
HashBcrypt bcrypt, cost 12 $2b$12$ followed by 53 characters
HashPbkdf2Sha256 PBKDF2-HMAC-SHA-256, 600,000 iterations $pbkdf2-sha256$i=600000,l=32$salt$hash

The defaults follow the OWASP Password Storage Cheat Sheet: Argon2id first, PBKDF2 where a rule such as FIPS 140 asks for it, and bcrypt only for systems that already use it. Measure Hash on your server and raise the cost with HashArgon2id when there is room.

Verify reads the algorithm from the string. It understands the strings above, Argon2i and Argon2d strings, and bcrypt strings that start with $2a$ or $2y$, so hashes made by PHP, Python, Node.js, Go or .NET libraries in these formats can be verified. The computed hash and the stored hash are compared without stopping at the first difference.

NeedsRehash is True for a hash that is not Argon2id version 19, or that uses less memory or fewer passes than Hash. Call it after a successful Verify, the one moment the password is known, to move old hashes to Argon2id.

TryVerify takes limits and tells why a password does not match. Its out parameter is a TPasswordVerificationOutcome: Match, Mismatch, Unsupported (damaged, an unknown format, or parameters outside the limits of the algorithm) or OutsideLimits (well formed, but outside the limits; nothing was computed). Log OutsideLimits, as it points at a hash that does not come from your own code or at limits that are too low.

var Outcome: TPasswordVerificationOutcome;
const Limits = TPasswordHashLimits.ForStoredHashes;
if not TPasswordHash.TryVerify(Password, StoredHash, Limits, Outcome) then
  LogFailedLogin(UserName, Outcome);

Details of the stored hashes:

  • A password is hashed as its UTF-8 bytes, without Unicode normalisation. Normalise first when users can type the same password on keyboards that compose characters differently.
  • bcrypt reads at most 72 bytes of a password. HashBcrypt raises for a longer password instead of cutting it off unnoticed. Verify cuts off at 72 bytes, as bcrypt itself does, so that existing hashes keep working.
  • The stored hash decides how much time and memory Verify takes, up to the limits below.
  • Verify returns False for a stored hash of more than 4,096 characters, for an Argon2 or PBKDF2 hash with a salt of fewer than 8 bytes or a hash of fewer than 16 bytes, and for a PBKDF2 hash that is not 32 bytes (l=32).
  • Salt and hash must be Base64 as Hash writes it, without bits set after the last byte. bcrypt salts are the exception: other libraries write bits there, and bcrypt ignores them.
  • The lanes of Argon2 are computed one after the other. A parallelism above 1 gives the correct hash but no speed.
  • The PBKDF2 string follows the PHC string format, as the Rust crate pbkdf2 writes it. It is not the format of passlib ($pbkdf2-sha256$29000$...) or Django.
  • There is no pepper parameter on TPasswordHash. TArgon2.Derive has the secret value of RFC 9106.

Limits

A stored hash and a message encrypted with a password name their own cost. A hash that reaches Verify from outside, a damaged row in a database, or a message from anyone, could ask for gigabytes of memory or hours of work. A message could also ask for a cost so low that it gives an attacker cheap guesses at the password. Crypto4D therefore turns down a cost outside the limits before it computes anything. TPasswordHashLimits has two sets of limits:

ForStoredHashes (Verify) ForMessages (TPasswordEncryption)
Argon2 memory at most 1 GiB (m = 1,048,576) from 19 MiB (m = 19,456) up to 256 MiB (m = 262,144)
Argon2 passes at most 10 from 2 up to 4
Argon2 memory times passes no limit of its own at most 512 MiB (m times t = 524,288)
Argon2 lanes at most 16 at most 16
bcrypt cost 16 does not apply
PBKDF2 10,000,000 iterations does not apply

The limits for stored hashes are well above the defaults of this library and of OWASP, and have no minimum, so that old hashes keep working until NeedsRehash moves them. The limits for messages are lower, because a message can come from anyone: 256 MiB with 2 passes, or 128 MiB with 4, is the most one message can cost. Their minimum is the cost of TArgon2Parameters.Recommended. The lanes of Argon2 are computed one after the other, so time and memory follow from m and t; the limit of 16 lanes keeps hashes made elsewhere with 4 or 8 lanes working and turns down absurd values.

Start from one of the two and change a field when your hashes are stronger, or to be stricter:

var Limits := TPasswordHashLimits.ForStoredHashes;
Limits.MaximumBcryptCost := 13;
var Outcome: TPasswordVerificationOutcome;
const IsMatch = TPasswordHash.TryVerify(Password, StoredHash, Limits, Outcome);

Big integers

uses
  Crypto4D.BigInteger;

const Modulus = TBigInteger.FromHex('ffffffff00000001000000000000000000000000ffffffffffffffffffffffff');
const Value   = TBigInteger.FromBytes(SomeBigEndianBytes);
const Inverse = Value.ModInverse(Modulus);
const Power   = Value.ModPow(TBigInteger.FromUInt64(65537), Modulus);

TBigInteger holds non-negative values of any size and is immutable.

Secrets and side channels

Signature verification works with public data only, so TBigInteger, the curve arithmetic and the DER reader make no attempt to run in constant time. Do not reuse them for anything that involves a secret.

The code that handles secrets:

  • AES is bitsliced: it has no lookup table and no branch that depends on the key or on the data. It is a translation of the constant-time implementation aes_ct64 of BearSSL.
  • GHASH, the authentication part of GCM, multiplies with masks and without a table that the key indexes.
  • The Base64 of salts and hashes in password hash strings is encoded and decoded with masks, without a branch or a table index that depends on the data.
  • A GCM tag is checked before anything is decrypted. Tags, password hashes and key commitments are compared without stopping at the first difference (TByteArrays.AreEqual).
  • Random bytes come from the operating system: BCryptGenRandom on Windows and getrandom on Linux. On Linux a call waits until the kernel has seeded its generator once after boot, and it repeats a read that a signal interrupts or that the kernel cuts short. When the operating system cannot deliver, ECrypto4DRandomError is raised; there is no fallback. Other platforms do not compile.

The library overwrites with zeros, when it is done with them, the heap buffers it allocates for secrets and the records and local arrays in which it keeps them:

  • AES: the expanded key, the key words of the key schedule, the bitsliced state and the copies that MixColumns makes of it, the keystream, the mask of the tag, the computed tag and the GHASH digest. GHASH: the hash key, its multiples and the state.
  • Argon2: all of its memory, the two blocks of every compression, the input of the first digest (which holds the password, the salt, the secret value and the associated data, written into one buffer), that digest, the inputs and the chained digests of the variable-length hash, and the last block.
  • BLAKE2b: the state, the message block in bytes and in words, the work vector and the digest in bytes.
  • bcrypt: the Blowfish subkeys and S-boxes, the key with its terminating zero, the words of the key and the salt that the key setup reads, and the encrypted magic text.
  • PBKDF2: the key, the digest of a password longer than 64 bytes, both padded keys, the THashSHA2 records of the inner and outer hash after every HMAC, the inner digest, every intermediate value U and every output block. THashSHA2 keeps its buffer and state inside the record, so clearing the record clears them.
  • TPasswordHash: the UTF-8 copy of the password and the hash that Verify computes.
  • TAes256GcmEncryption and TPasswordEncryption: the UTF-8 copy of a password or of a text to encrypt, the decrypted bytes behind TryDecryptString, and the key and the commitment that Argon2id derives from a password.

A test replaces the memory manager while Argon2, PBKDF2, TPasswordHash and TPasswordEncryption.TryDecrypt run and checks that no heap block they release still holds the password, the derived key or an intermediate chain value.

What it does not do:

  • No measurement backs the constant-time claim. It rests on how the source is written, and a compiler is free to turn such code into something else.
  • bcrypt looks up the Blowfish S-boxes with indexes that depend on the password, and Argon2id reads memory at addresses that depend on the password after its first half pass. Both follow from how these algorithms are defined.
  • A Delphi string cannot be wiped reliably. The password or text you pass in, the text that TryDecryptString returns, and the key you hold in a TBytes, stay in memory until you overwrite them or the memory is reused. Call TByteArrays.Wipe on your own key buffers and on decrypted bytes when you are done with them.
  • The stack and the registers are not wiped. Single local values, the intermediate values of the bitsliced S-box and of the GHASH multiplication, temporary copies that the compiler makes of a record, and the message schedule and working variables inside the SHA-256 compression of System.Hash can stay on the stack until the next call reuses it.
  • Memory is not locked, so the operating system can write it to the page file or to a crash dump.

Testing

The test project is tests\Crypto4D.Tests.dproj, a DUnitX console application. The Debug configuration has overflow and range checking switched on.

The tests were run with Delphi 13, as Debug and as Release build, for Win32, Win64 and Linux64, and on Win32 and Win64 also as Release build with overflow and range checking switched on. The Linux64 build was made with the SDK of Ubuntu 24.04 and run on Ubuntu 24.04 under WSL 2. No other Delphi version and no other platform was run. CONTRIBUTING.md says how to build and run them.

What the tests cover:

  • Wycheproof test vectors for ECDSA P-256 with SHA-256 (DER and P1363), Ed25519 and RSA PKCS#1 v1.5 with SHA-256 for 2048, 3072, 4096 and 8192 bit keys. Every valid vector must verify and every invalid vector must be rejected.
  • The Ed25519 test vectors of RFC 8032 section 7.1.
  • The 914 Ed25519 vectors of C2SP CCTV, which cover the edge cases of the public key and of R. Crypto4D rejects every vector with the flag low_order_A, non_canonical_A, non_canonical_R or low_order_residue and accepts the other 86.
  • The 12 cases of ed25519-speccheck. Crypto4D accepts cases 2 and 3 and rejects the other ten; tests\vectors\ed25519-speccheck\SOURCE.md gives the reason per case.
  • The 1,024 signatures of the regression test sign.input from ed25519.cr.yp.to. All verify, and none verifies after one bit of the signature is flipped.
  • NIST CAVP signature verification vectors: 15 for ECDSA with P-256 and SHA-256, and 35 for RSA PKCS#1 v1.5 with SHA-256 and a 2048 or 3072 bit modulus.
  • 52 pairs of a certificate and its issuer certificate from x509-limbo, with the outcome of the Python package cryptography as expectation. The selection includes signatures that do not match, algorithms and key sizes that Crypto4D does not support, and a P-256 key with explicit curve parameters, which Crypto4D rejects.
  • A cross-check against OpenSSL: 2,960 cases with keys and signatures made by OpenSSL. About half are damaged by flipping one bit in the signature, the message or the public key. OpenSSL decides the expected outcome of every case.
  • Big integer arithmetic against results computed by an independent arbitrary-precision implementation, including divisions that need the rare add-back step of Knuth's algorithm D.
  • X.509 certificates made by OpenSSL, compared with what OpenSSL reports about them, plus damaged and truncated variants.
  • Sizes beyond 2^31: a 4 GiB message, a 2 GiB DER element, an RSA modulus of more than 2^32 bits and an AES-GCM message of more than 2^32 bits, checked against OpenSSL.
  • AES: the three example vectors of FIPS 197 appendix C.
  • AES-GCM: the 2,250 NIST CAVP vectors with a 96 bit nonce and a 128 bit tag, for keys of 128, 192 and 256 bits. The 1,673 authentic ones must seal to the same bytes and open to the same plaintext, and the 577 with a wrong tag must be rejected. Also the 197 Wycheproof AES-GCM vectors with those two lengths, and 375 messages sealed by OpenSSL through the Python package cryptography, up to 70,001 bytes long.
  • AES-GCM and TAes256GcmEncryption: a message with any single bit flipped is rejected.
  • BLAKE2b: the vector of RFC 7693 appendix A, the 256 unkeyed known answers of the BLAKE2 reference repository and 84 digests of other lengths computed by Python.
  • Argon2: the three test vectors of RFC 9106 section 5 and 186 cases computed by OpenSSL for the three variants, from 8 KiB up to 19 MiB of memory, with 1 up to 4 lanes.
  • bcrypt: the 12 entries of the test table of crypt_blowfish that are plain bcrypt, and 48 hash strings made by the Python package bcrypt.
  • PBKDF2-HMAC-SHA-256: the 60 Wycheproof vectors, which include those of RFC 7914, and 211 cases computed by Python, one of them with 600,000 iterations.
  • Password hash strings: 27 Argon2id strings made by cryptography and the bcrypt strings above must verify with the right password and must not verify with another one. 39 damaged or unsupported strings, and a string of more than 4,096 characters, must be rejected.
  • Limits: for each limit, a hash or a message exactly at the limit is accepted and one step outside it is turned down with OutsideLimits, also for an Argon2 hash that asks for 2 TiB, which would raise EOutOfMemory if it were computed.
  • Encrypting with a password: the round trip, a wrong password, a changed byte in every field of the format, a message whose tag is valid but whose key commitment belongs to another password, unknown versions, parameters above the limits and below the minimum, messages that are too short, Base64 that is not exact and a plaintext that is not UTF-8, each with the outcome it reports.
  • Wiping: the heap check described under Secrets and side channels.
  • Base64 of password hash strings: encoding of all 64 values, decoding of every one of the 65,536 UTF-16 code units for both alphabets, and rejecting bits after the last byte.

The vectors are in tests\vectors. Every folder there has a SOURCE.md that says where the data comes from.

Wycheproof vectors with the result "acceptable"

Wycheproof marks a vector acceptable when a library may accept or reject it. Crypto4D decides per flag:

Flag Vectors Crypto4D Reason
MissingNull (RSA) 4 rejects The DigestInfo has no NULL parameter. Wycheproof calls these signatures invalid but tolerated by some legacy libraries. Crypto4D compares against the one correct encoding.
SmallOrderPublicKey (Ed25519) 8 rejects The public key is one of the eight points of small order. Crypto4D rejects such keys.
MixedOrderPublicKey (Ed25519) 21 accepts all 21 The public key has a torsion component but is not of small order, so Crypto4D does not reject the key. Each of these signatures also satisfies the equation without the cofactor, which an independent implementation confirmed (see tests\vectors\wycheproof\SOURCE.md).

License

MIT, see LICENSE.

src\Crypto4D.Aes.pas is a translation of code from BearSSL, copyright (c) 2016 Thomas Pornin, which is also under the MIT license. The unit starts with its copyright and permission notice.

Test vectors from other projects keep their own license. The vectors in tests\vectors\wycheproof, tests\vectors\ed25519-speccheck and tests\vectors\x509-limbo are licensed under the Apache License 2.0 and those in tests\vectors\cctv under a BSD 3-Clause license; each of these folders has a LICENSE file. SOURCE.md in tests\vectors\ed25519-cr-yp-to, tests\vectors\nist-cavp, tests\vectors\blake2 and tests\vectors\crypt-blowfish states the terms of those vectors.

Contributing and security

See CONTRIBUTING.md and, for reporting a vulnerability, SECURITY.md.

About

Signature verification in pure Delphi: ECDSA P-256, RSA PKCS#1 v1.5, Ed25519 and X.509 certificates

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages