From bef67a748f41a10c8d0277e426cf1a16d9520b00 Mon Sep 17 00:00:00 2001 From: Ugochukwu Mmaduekwe Date: Tue, 24 Nov 2026 10:37:27 +0100 Subject: [PATCH 1/2] Blind and fix the timing of DH, DSA and related scalar arithmetic Diffie-Hellman agreements and DSA/ECDSA/ECNR signing exponentiate a secret with a base the peer or verifier can choose, so their variable-time modular powers could be accumulated against the key over many runs. The base raised to a long-term key is now blinded, the DSA nonce exponent is blinded with a random multiple of q, and each signature's s is formed with fixed-time modular arithmetic kept off the value-dependent BigInteger.Mod. Adds fixed-time ModAdd, ModSubtract, ModMult and ModPowBaseBlinded to the BigInteger utilities, backed by a constant-time Montgomery multiply over a fixed number of words, and a CreateBlindedExponent helper. Also: - DsaPrivateKeyParameters requires x in [1, q-1]. - DH key generation refuses a private value length below twice the security strength of p (SP 800-56A), unless the new TCryptoLibConfig.DH.AllowShortPrivateValue opt-out is set; l may now equal the bit length of p, per PKCS#3. - DHBasicAgreement re-validates a subclassed peer public key by construction, so range and subgroup checks cannot be bypassed. - The binary-polynomial scalar multiply wipes its scratch table. - MiscPemGenerator fails closed when an algorithm is given with no password. - BigInteger.ModInversePow2 lifts the inverse a word at a time. --- CryptoLib.Tests/src/Crypto/DHTests.pas | 35 +++- CryptoLib.Tests/src/Crypto/DSATests.pas | 33 +++ CryptoLib.Tests/src/Math/BigIntegerTests.pas | 44 ++++ .../src/OpenSsl/OpenSslWriterTests.pas | 27 +++ .../src/Crypto/Agreements/ClpDHAgreement.pas | 9 +- .../Crypto/Agreements/ClpDHBasicAgreement.pas | 34 ++- .../src/Crypto/Generators/ClpDHGenerators.pas | 8 +- .../Generators/ClpDHKeyGeneratorHelper.pas | 68 ++++++ .../src/Crypto/Parameters/ClpDHParameters.pas | 5 +- .../Crypto/Parameters/ClpDsaParameters.pas | 10 +- CryptoLib/src/Crypto/Signers/ClpDsaSigner.pas | 19 +- .../src/Crypto/Signers/ClpECDsaSigner.pas | 7 +- .../src/Crypto/Signers/ClpECNRSigner.pas | 4 +- .../Math/BinPoly/ClpBinPolyScalarBackend.pas | 12 +- CryptoLib/src/Math/ClpBigInteger.pas | 75 +++++-- CryptoLib/src/Math/ClpBigIntegerUtilities.pas | 196 +++++++++++++++++- CryptoLib/src/Misc/ClpCryptoLibConfig.pas | 21 ++ .../OpenSsl/ClpOpenSslMiscPemGenerator.pas | 3 + 18 files changed, 552 insertions(+), 58 deletions(-) diff --git a/CryptoLib.Tests/src/Crypto/DHTests.pas b/CryptoLib.Tests/src/Crypto/DHTests.pas index be410a56..ed09b43c 100644 --- a/CryptoLib.Tests/src/Crypto/DHTests.pas +++ b/CryptoLib.Tests/src/Crypto/DHTests.pas @@ -63,6 +63,7 @@ interface ClpIX9DHAsn1Objects, ClpX9DHAsn1Objects, ClpBigInteger, + ClpCryptoLibConfig, ClpCryptoLibTypes, ClpCryptoLibExceptions, CryptoLibTestBase; @@ -142,6 +143,7 @@ TTestDH = class(TCryptoLibAlgorithmTestCase) procedure TestDHSubgroupConfinement; procedure TestModulusSizeBound; procedure TestDHBounds; + procedure TestPrivateValueLengthFloor; procedure TestDHPgenCounterBound; procedure TestDHMaliciousMessage; end; @@ -477,8 +479,9 @@ procedure TTestDH.TestDHBounds; l2 := 1024; try + // PKCS#3 allows l up to bitlength(p), so an oversized l is one past that TDHKeyGenerationParameters.Create(random, - TDHParameters.Create(p2, g2, TBigInteger.GetDefault, l2) as IDHParameters); + TDHParameters.Create(p2, g2, TBigInteger.GetDefault, l2 + 1) as IDHParameters); Fail('oversized DH ''l'' value accepted'); except on E: EArgumentCryptoLibException do @@ -693,7 +696,8 @@ procedure TTestDH.TestDHSubgroupConfinement; agreeOk := True; except on E: EArgumentCryptoLibException do - if Pos('weak', E.Message) = 0 then + // the agreement now re-validates a subclassed peer key by construction, same as the constructor path + if Pos('invalid DH public key', E.Message) = 0 then Fail('wrong CalculateAgreement exception message: ' + E.Message); end; if agreeOk then @@ -701,6 +705,33 @@ procedure TTestDH.TestDHSubgroupConfinement; end; end; +procedure TTestDH.TestPrivateValueLengthFloor; +var + params: IDHParameters; + kpGen: IDHBasicKeyPairGenerator; + LRaised: Boolean; +begin + params := Ike2048; + // for a 2048-bit p the floor is 2 * 112 = 224 bits, so l = 100 is too short + LRaised := False; + try + GetDHBasicKeyPairGenerator(params.G, params.P, 100); + except + on E: EArgumentCryptoLibException do + LRaised := True; + end; + CheckTrue(LRaised, 'short DH private value length not rejected'); + + // the opt-out accepts it + TCryptoLibConfig.DH.AllowShortPrivateValue := True; + try + kpGen := GetDHBasicKeyPairGenerator(params.G, params.P, 100); + CheckTrue(kpGen <> nil, 'generator not created with opt-out'); + finally + TCryptoLibConfig.DH.AllowShortPrivateValue := False; + end; +end; + function TTestDH.GetDHBasicKeyPairGenerator(const g, p: TBigInteger; privateValueSize: Int32): IDHBasicKeyPairGenerator; var diff --git a/CryptoLib.Tests/src/Crypto/DSATests.pas b/CryptoLib.Tests/src/Crypto/DSATests.pas index 606fe12e..43a2f1ec 100644 --- a/CryptoLib.Tests/src/Crypto/DSATests.pas +++ b/CryptoLib.Tests/src/Crypto/DSATests.pas @@ -136,6 +136,7 @@ TTestDSA = class(TCryptoLibAlgorithmTestCase) procedure TestDsa2Parameters; procedure TestKeyGenerationAll; procedure TestParameters; + procedure TestPrivateKeyRange; procedure TestModulusSizeBound; /// @@ -1167,6 +1168,38 @@ procedure TDSATestSecureRandom.NextBytes(const bytes: TBytes); end; +procedure TTestDSA.TestPrivateKeyRange; +var + LParams: IDsaParameters; + LPriv: IDsaPrivateKeyParameters; + LRaised: Boolean; +begin + // TDsaParameters does not check primality, so trivial domain values suffice to exercise the x range + LParams := TDsaParameters.Create(TBigInteger.ValueOf(23), TBigInteger.ValueOf(11), + TBigInteger.ValueOf(4)) as IDsaParameters; + + LRaised := False; + try + LPriv := TDsaPrivateKeyParameters.Create(TBigInteger.Zero, LParams) as IDsaPrivateKeyParameters; + except + on E: EArgumentCryptoLibException do + LRaised := True; + end; + CheckTrue(LRaised, 'x = 0 not rejected'); + + LRaised := False; + try + LPriv := TDsaPrivateKeyParameters.Create(LParams.Q, LParams) as IDsaPrivateKeyParameters; + except + on E: EArgumentCryptoLibException do + LRaised := True; + end; + CheckTrue(LRaised, 'x = q not rejected'); + + LPriv := TDsaPrivateKeyParameters.Create(TBigInteger.ValueOf(5), LParams) as IDsaPrivateKeyParameters; + CheckTrue(LPriv.X.Equals(TBigInteger.ValueOf(5)), 'valid x rejected'); +end; + initialization // Register any test cases with the test runner diff --git a/CryptoLib.Tests/src/Math/BigIntegerTests.pas b/CryptoLib.Tests/src/Math/BigIntegerTests.pas index b592b9c1..d867b7ba 100644 --- a/CryptoLib.Tests/src/Math/BigIntegerTests.pas +++ b/CryptoLib.Tests/src/Math/BigIntegerTests.pas @@ -34,6 +34,7 @@ interface ClpSecureRandom, ClpISecureRandom, ClpBigInteger, + ClpBigIntegerUtilities, ClpCryptoLibTypes, ClpCryptoLibExceptions, CryptoLibTestBase; @@ -104,6 +105,7 @@ TTestBigInteger = class(TCryptoLibAlgorithmTestCase) procedure TestToString(); procedure TestValueOf(); procedure TestXor(); + procedure TestModArithmeticAndBlinding(); end; implementation @@ -1495,6 +1497,48 @@ procedure TTestBigInteger.TestXor; end; end; +procedure TTestBigInteger.TestModArithmeticAndBlinding(); +var + LM, LX, LY, LE: TBigInteger; + LModuli: TCryptoLibGenericArray; + LI, LJ: Int32; + LRaised: Boolean; +begin + // small odd primes and the secp256r1 field prime + LModuli := TCryptoLibGenericArray.Create(TBigInteger.ValueOf(5), + TBigInteger.ValueOf(7), TBigInteger.Create( + 'FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF', 16)); + + for LI := 0 to System.High(LModuli) do + begin + LM := LModuli[LI]; + for LJ := 0 to 49 do + begin + LX := TBigIntegerUtilities.CreateRandomInRange(Fzero, LM.Subtract(Fone), FRandom); + LY := TBigIntegerUtilities.CreateRandomInRange(Fzero, LM.Subtract(Fone), FRandom); + CheckTrue(TBigIntegerUtilities.ModAdd(LM, LX, LY).Equals(LX.Add(LY).&Mod(LM)), 'ModAdd'); + CheckTrue(TBigIntegerUtilities.ModSubtract(LM, LX, LY).Equals(LX.Subtract(LY).&Mod(LM)), 'ModSubtract'); + CheckTrue(TBigIntegerUtilities.ModMult(LM, LX, LY).Equals(LX.Multiply(LY).&Mod(LM)), 'ModMult'); + end; + + // base-blinded exponentiation matches plain ModPow for a prime modulus + LX := TBigIntegerUtilities.CreateRandomInRange(Fone, LM.Subtract(Fone), FRandom); + LE := TBigInteger.ValueOf(65537); + CheckTrue(TBigIntegerUtilities.ModPowBaseBlinded(LM, LX, LE, FRandom).Equals(LX.ModPow(LE, LM)), + 'ModPowBaseBlinded'); + end; + + // operands outside [0, M) are rejected rather than reduced + LRaised := False; + try + TBigIntegerUtilities.ModAdd(TBigInteger.ValueOf(7), TBigInteger.ValueOf(7), Fone); + except + on E: EArgumentCryptoLibException do + LRaised := True; + end; + CheckTrue(LRaised, 'out-of-range operand not rejected'); +end; + initialization // Register any test cases with the test runner diff --git a/CryptoLib.Tests/src/OpenSsl/OpenSslWriterTests.pas b/CryptoLib.Tests/src/OpenSsl/OpenSslWriterTests.pas index 642d6e03..3ab8746f 100644 --- a/CryptoLib.Tests/src/OpenSsl/OpenSslWriterTests.pas +++ b/CryptoLib.Tests/src/OpenSsl/OpenSslWriterTests.pas @@ -37,6 +37,7 @@ interface ClpIPemObject, ClpIOpenSslPemWriter, ClpOpenSslPemWriter, + ClpCryptoLibExceptions, ClpIOpenSslPemReader, ClpOpenSslPemReader, ClpIOpenSslPasswordFinder, @@ -87,6 +88,7 @@ TOpenSslWriterTest = class(TCryptoLibAlgorithmTestCase) procedure TestWriteReadEcKeyGenerated; procedure TestWritePemObjectOverride; procedure TestEncryptedWriteRead; + procedure TestEncryptedWriteNilPasswordRejected; end; implementation @@ -296,6 +298,31 @@ procedure TOpenSslWriterTest.TestWritePemObjectOverride; end; end; +procedure TOpenSslWriterTest.TestEncryptedWriteNilPasswordRejected; +var + LStream: TStringStream; + LWriter: IOpenSslPemWriter; + LRandom: ISecureRandom; + LRaised: Boolean; +begin + LRandom := TCryptoServicesRegistrar.GetSecureRandom(); + LStream := TStringStream.Create('', TEncoding.ASCII); + try + LWriter := TOpenSslPemWriter.Create(LStream); + LRaised := False; + try + LWriter.WriteObject(TValue.From(GetTestRsaKey), + 'AES-128-CBC', nil, LRandom); + except + on E: EArgumentNilCryptoLibException do + LRaised := True; + end; + CheckTrue(LRaised, 'an algorithm with a nil password was not rejected'); + finally + LStream.Free; + end; +end; + initialization {$IFDEF FPC} diff --git a/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas b/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas index ab09980c..fb74836e 100644 --- a/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas +++ b/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas @@ -23,6 +23,7 @@ interface uses SysUtils, ClpBigInteger, + ClpBigIntegerUtilities, ClpISecureRandom, ClpCryptoServicesRegistrar, ClpICipherParameters, @@ -98,7 +99,7 @@ implementation function TDHAgreement.CalculateAgreement(const APub: IDHPublicKeyParameters; const AMessage: TBigInteger): TBigInteger; var - LP, LPeerY, LPeerMessage: TBigInteger; + LP, LPeerY, LPeerMessage, LStaticPart: TBigInteger; LParameter: IDHPublicKeyParameters; LPubConcrete: TDHPublicKeyParameters; begin @@ -130,12 +131,16 @@ function TDHAgreement.CalculateAgreement(const APub: IDHPublicKeyParameters; else LPeerY := TDHPublicKeyParameters.Create(APub.Y, FDhParams).Y; + // our ephemeral value is used once, so nothing accumulates against it and this exponentiation is left as it is Result := LPeerY.ModPow(FPrivateValue, LP); if Result.Equals(TBigInteger.One) then raise EInvalidOperationCryptoLibException.CreateRes(@SSharedKeyInvalid); - Result := LPeerMessage.ModPow(FKey.X, LP).Multiply(Result).&Mod(LP); + // the peer chooses the base raised to the long-term key, so that base is blinded: the variable-time ModPow's + // timing could otherwise be accumulated against the key over many agreements + LStaticPart := TBigIntegerUtilities.ModPowBaseBlinded(LP, LPeerMessage, FKey.X, FRandom); + Result := LStaticPart.Multiply(Result).&Mod(LP); end; function TDHAgreement.CalculateMessage: TBigInteger; diff --git a/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas b/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas index 875ef978..9122edec 100644 --- a/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas +++ b/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas @@ -23,10 +23,14 @@ interface uses SysUtils, ClpBigInteger, + ClpBigIntegerUtilities, + ClpISecureRandom, + ClpCryptoServicesRegistrar, ClpICipherParameters, ClpIBasicAgreement, ClpIDHBasicAgreement, ClpIDHParameters, + ClpDHParameters, ClpIParametersWithRandom, ClpCryptoLibExceptions; @@ -36,7 +40,6 @@ interface SNotDHPrivateKeyParameters = 'DHEngine expects DHPrivateKeyParameters'; SAlgorithmNotInitialized = 'agreement algorithm not initialized'; SSharedKeyInvalid = 'shared key cannot be 1'; - SDHPublicKeyWeak = 'Diffie-Hellman public key is weak'; type /// @@ -56,6 +59,7 @@ TDHBasicAgreement = class(TInterfacedObject, IDHBasicAgreement, var FKey: IDHPrivateKeyParameters; FDhParams: IDHParameters; + FRandom: ISecureRandom; public /// @@ -84,6 +88,7 @@ function TDHBasicAgreement.CalculateAgreement(const APubKey: ICipherParameters) : TBigInteger; var LPub: IDHPublicKeyParameters; + LPubConcrete: TDHPublicKeyParameters; LP, LPeerY: TBigInteger; begin if (FKey = nil) then @@ -98,13 +103,17 @@ function TDHBasicAgreement.CalculateAgreement(const APubKey: ICipherParameters) LP := FDhParams.P; - LPeerY := LPub.Y; + // a normally-constructed public key already validated its Y (range, and subgroup when q is present); Y is + // overridable, so re-validate by construction unless pub is exactly the base type + LPubConcrete := LPub as TDHPublicKeyParameters; + if LPubConcrete.ClassType = TDHPublicKeyParameters then + LPeerY := LPub.Y + else + LPeerY := TDHPublicKeyParameters.Create(LPub.Y, FDhParams).Y; - if ((not LPeerY.IsInitialized) or (LPeerY.CompareTo(TBigInteger.One) <= 0) or - (LPeerY.CompareTo(LP.Subtract(TBigInteger.One)) >= 0)) then - raise EArgumentCryptoLibException.CreateRes(@SDHPublicKeyWeak); - - Result := LPeerY.ModPow(FKey.X, LP); + // the exponent is our private value, long lived for static-static agreement, and the peer chooses the base, + // so blind the base: the variable-time ModPow's timing could otherwise be accumulated against the key + Result := TBigIntegerUtilities.ModPowBaseBlinded(LP, LPeerY, FKey.X, FRandom); if Result.Equals(TBigInteger.One) then raise EInvalidOperationCryptoLibException.CreateRes(@SSharedKeyInvalid); @@ -121,9 +130,16 @@ procedure TDHBasicAgreement.Init(const AParameters: ICipherParameters); LWithRandom: IParametersWithRandom; LDHPriv: IDHPrivateKeyParameters; begin - LParameters := AParameters; - if Supports(LParameters, IParametersWithRandom, LWithRandom) then + if Supports(AParameters, IParametersWithRandom, LWithRandom) then + begin + FRandom := LWithRandom.Random; LParameters := LWithRandom.Parameters; + end + else + begin + FRandom := TCryptoServicesRegistrar.GetSecureRandom(); + LParameters := AParameters; + end; if not Supports(LParameters, IDHPrivateKeyParameters, LDHPriv) then raise EArgumentCryptoLibException.CreateRes(@SNotDHPrivateKeyParameters); diff --git a/CryptoLib/src/Crypto/Generators/ClpDHGenerators.pas b/CryptoLib/src/Crypto/Generators/ClpDHGenerators.pas index 64e210b7..11e933e4 100644 --- a/CryptoLib/src/Crypto/Generators/ClpDHGenerators.pas +++ b/CryptoLib/src/Crypto/Generators/ClpDHGenerators.pas @@ -75,8 +75,7 @@ function TDHKeyPairGenerator.GenerateKeyPair: IAsymmetricCipherKeyPair; LX, LY: TBigInteger; begin LDhp := FParam.Parameters; - LX := TDHKeyGeneratorHelper.CalculatePrivate(LDhp, FParam.Random); - LY := TDHKeyGeneratorHelper.CalculatePublic(LDhp, LX); + TDHKeyGeneratorHelper.CalculateKeyPair(LDhp, FParam.Random, LX, LY); Result := TAsymmetricCipherKeyPair.Create(TDHPublicKeyParameters.Create(LY, LDhp) as IDHPublicKeyParameters, TDHPrivateKeyParameters.Create(LX, LDhp) as IDHPrivateKeyParameters); @@ -88,6 +87,7 @@ procedure TDHKeyPairGenerator.Init(const AParameters: IKeyGenerationParameters); raise EArgumentNilCryptoLibException.CreateRes(@SParametersCannotBeNil); if not Supports(AParameters, IDHKeyGenerationParameters, FParam) then raise EArgumentNilCryptoLibException.CreateRes(@SParametersCannotBeNil); + TDHKeyGeneratorHelper.CheckPrivateValueLength(FParam.Parameters.P, FParam.Parameters.L); end; function TDHBasicKeyPairGenerator.GenerateKeyPair: IAsymmetricCipherKeyPair; @@ -96,8 +96,7 @@ function TDHBasicKeyPairGenerator.GenerateKeyPair: IAsymmetricCipherKeyPair; LX, LY: TBigInteger; begin LDhp := FParam.Parameters; - LX := TDHKeyGeneratorHelper.CalculatePrivate(LDhp, FParam.Random); - LY := TDHKeyGeneratorHelper.CalculatePublic(LDhp, LX); + TDHKeyGeneratorHelper.CalculateKeyPair(LDhp, FParam.Random, LX, LY); Result := TAsymmetricCipherKeyPair.Create(TDHPublicKeyParameters.Create(LY, LDhp) as IDHPublicKeyParameters, TDHPrivateKeyParameters.Create(LX, LDhp) as IDHPrivateKeyParameters); @@ -109,6 +108,7 @@ procedure TDHBasicKeyPairGenerator.Init(const AParameters: IKeyGenerationParamet raise EArgumentNilCryptoLibException.CreateRes(@SParametersCannotBeNil); if not Supports(AParameters, IDHKeyGenerationParameters, FParam) then raise EArgumentNilCryptoLibException.CreateRes(@SParametersCannotBeNil); + TDHKeyGeneratorHelper.CheckPrivateValueLength(FParam.Parameters.P, FParam.Parameters.L); end; function TDHParametersGenerator.GenerateParameters: IDHParameters; diff --git a/CryptoLib/src/Crypto/Generators/ClpDHKeyGeneratorHelper.pas b/CryptoLib/src/Crypto/Generators/ClpDHKeyGeneratorHelper.pas index 462ecc6b..1d880acb 100644 --- a/CryptoLib/src/Crypto/Generators/ClpDHKeyGeneratorHelper.pas +++ b/CryptoLib/src/Crypto/Generators/ClpDHKeyGeneratorHelper.pas @@ -21,26 +21,94 @@ interface uses + SysUtils, ClpISecureRandom, ClpBitOperations, ClpBigInteger, ClpBigIntegerUtilities, + ClpCryptoLibConfig, ClpWNafUtilities, + ClpCryptoLibExceptions, ClpIDHParameters; +resourcestring + SPrivateValueLengthTooShort = + 'when l value specified, it must not be less than %d for a %d bit p'; + type TDHKeyGeneratorHelper = class sealed(TObject) public + // the security strength s of p, in bits (SP 800-56A Appendix D steps from 4096 bits up, SP 800-57 below). + class function SecurityStrengthFor(const AP: TBigInteger): Int32; static; + // refuse a private value length l below twice the security strength of p, unless the config allows it. + class procedure CheckPrivateValueLength(const AP: TBigInteger; AL: Int32); static; class function CalculatePrivate(const ADHParams: IDHParameters; const ARandom: ISecureRandom): TBigInteger; static; class function CalculatePublic(const ADHParams: IDHParameters; const AX: TBigInteger): TBigInteger; static; + // generate x and y, redrawing while y falls outside [2, p - 2]. + class procedure CalculateKeyPair(const ADHParams: IDHParameters; const ARandom: ISecureRandom; + out AX, AY: TBigInteger); static; end; implementation { TDHKeyGeneratorHelper } +class function TDHKeyGeneratorHelper.SecurityStrengthFor(const AP: TBigInteger): Int32; +var + LPBits: Int32; +begin + LPBits := AP.BitLength; + if LPBits >= 15360 then + Result := 256 + else if LPBits >= 8192 then + Result := 200 // SP 800-56A Appendix D + else if LPBits >= 7680 then + Result := 192 + else if LPBits >= 6144 then + Result := 176 // SP 800-56A Appendix D + else if LPBits >= 4096 then + Result := 152 // SP 800-56A Appendix D + else if LPBits >= 3072 then + Result := 128 + else if LPBits >= 2048 then + Result := 112 + else if LPBits >= 1024 then + Result := 80 + else + Result := 20; +end; + +class procedure TDHKeyGeneratorHelper.CheckPrivateValueLength(const AP: TBigInteger; AL: Int32); +var + LMinL: Int32; +begin + if AL = 0 then + Exit; + + LMinL := 2 * SecurityStrengthFor(AP); + if (AL < LMinL) and (not TCryptoLibConfig.DH.AllowShortPrivateValue) then + raise EArgumentCryptoLibException.CreateResFmt(@SPrivateValueLengthTooShort, + [LMinL, AP.BitLength]); +end; + +class procedure TDHKeyGeneratorHelper.CalculateKeyPair(const ADHParams: IDHParameters; + const ARandom: ISecureRandom; out AX, AY: TBigInteger); +var + LPSub2: TBigInteger; +begin + // DHParameters already requires g in [2, p - 2], so a suitable x always exists + LPSub2 := ADHParams.P.Subtract(TBigInteger.Two); + while True do + begin + AX := CalculatePrivate(ADHParams, ARandom); + AY := CalculatePublic(ADHParams, AX); + if (AY.CompareTo(TBigInteger.Two) >= 0) and (AY.CompareTo(LPSub2) <= 0) then + Exit; + end; +end; + class function TDHKeyGeneratorHelper.CalculatePrivate(const ADHParams: IDHParameters; const ARandom: ISecureRandom): TBigInteger; var diff --git a/CryptoLib/src/Crypto/Parameters/ClpDHParameters.pas b/CryptoLib/src/Crypto/Parameters/ClpDHParameters.pas index cf48bcc7..aa5ee6d8 100644 --- a/CryptoLib/src/Crypto/Parameters/ClpDHParameters.pas +++ b/CryptoLib/src/Crypto/Parameters/ClpDHParameters.pas @@ -46,7 +46,7 @@ interface SInvalidGeneratorRange = 'generator must be in the range [2, p - 2]'; SQTooBigToBeAFactor = 'Q too big to be a factor of (P - 1)'; SMTooBig = 'M value must be < bitLength of P'; - SLErrorOne = 'when L value specified, it must be less than bitLength(P)'; + SLErrorOne = 'when L value specified, it must not be greater than bitLength(P)'; SLErrorTwo = 'when L value specified, it may not be less than M value'; SInvalidSubGroupFactor = 'subgroup factor must be >= 2'; SSeedNil = 'seed cannot be nil'; @@ -393,7 +393,8 @@ constructor TDHParameters.Create(const AP, AG, AQ: TBigInteger; AM, AL: Int32; if (AL <> 0) then begin - if (AL >= AP.BitLength) then + // PKCS#3 sec. 6: 2^(l-1) <= p, so l may be up to the bit length of p + if (AL > AP.BitLength) then begin raise EArgumentCryptoLibException.CreateRes(@SLErrorOne); end; diff --git a/CryptoLib/src/Crypto/Parameters/ClpDsaParameters.pas b/CryptoLib/src/Crypto/Parameters/ClpDsaParameters.pas index 4743008f..c5164d16 100644 --- a/CryptoLib/src/Crypto/Parameters/ClpDsaParameters.pas +++ b/CryptoLib/src/Crypto/Parameters/ClpDsaParameters.pas @@ -43,6 +43,7 @@ interface SDsaModulusOutOfRange = 'DSA modulus out of range'; SInvalidYInCorrectGroup = 'Y value does not appear to be in the correct group'; SXUninitialized = 'X cannot be uninitialized'; + SDsaXOutOfRange = 'x must be in [1, q-1]'; type TDsaValidationParameters = class(TInterfacedObject, IDsaValidationParameters) @@ -153,7 +154,7 @@ TDsaPrivateKeyParameters = class sealed(TDsaKeyParameters, function GetX: TBigInteger; inline; - class function Validate(const AX: TBigInteger): TBigInteger; static; inline; + class function Validate(const AX: TBigInteger; const AParameters: IDsaParameters): TBigInteger; static; public constructor Create(const AX: TBigInteger; const AParameters: IDsaParameters); @@ -466,12 +467,15 @@ function TDsaPrivateKeyParameters.GetX: TBigInteger; Result := FX; end; -class function TDsaPrivateKeyParameters.Validate(const AX: TBigInteger): TBigInteger; +class function TDsaPrivateKeyParameters.Validate(const AX: TBigInteger; const AParameters: IDsaParameters): TBigInteger; begin if (not AX.IsInitialized) then begin raise EArgumentNilCryptoLibException.CreateRes(@SXUninitialized); end; + // FIPS 186-4 sec. 4.1: x is in [1, q-1]. Parameters may be nil (inherited), leaving nothing to check. + if (AParameters <> nil) and ((AX.SignValue < 1) or (AX.CompareTo(AParameters.Q) >= 0)) then + raise EArgumentCryptoLibException.CreateRes(@SDsaXOutOfRange); Result := AX; end; @@ -479,7 +483,7 @@ constructor TDsaPrivateKeyParameters.Create(const AX: TBigInteger; const AParameters: IDsaParameters); begin inherited Create(True, AParameters); - FX := Validate(AX); + FX := Validate(AX, AParameters); end; function TDsaPrivateKeyParameters.Equals(const AOther: IDsaPrivateKeyParameters): Boolean; diff --git a/CryptoLib/src/Crypto/Signers/ClpDsaSigner.pas b/CryptoLib/src/Crypto/Signers/ClpDsaSigner.pas index b1c46baf..3b918da9 100644 --- a/CryptoLib/src/Crypto/Signers/ClpDsaSigner.pas +++ b/CryptoLib/src/Crypto/Signers/ClpDsaSigner.pas @@ -135,11 +135,12 @@ function TDsaSigner.GenerateSignature(const AMessage: TCryptoLibByteArray) : TCryptoLibGenericArray; var LParameters: IDsaParameters; - LQ, LM, LX, LK, LR, LS: TBigInteger; + LQ, LM, LX, LK, LBlindedK, LR, LS: TBigInteger; begin LParameters := FKey.Parameters; LQ := LParameters.Q; - LM := CalculateE(LQ, AMessage); + // m is public, and CalculateE can leave it at or past q, which ModAdd below rejects rather than reduces + LM := CalculateE(LQ, AMessage).&Mod(LQ); LX := (FKey as IDsaPrivateKeyParameters).X; if (FKCalculator.IsDeterministic) then @@ -153,11 +154,14 @@ function TDsaSigner.GenerateSignature(const AMessage: TCryptoLibByteArray) LK := FKCalculator.NextK(); - LR := LParameters.G.ModPow(LK, LParameters.P).&Mod(LQ); - - LK := TBigIntegerUtilities.ModOddInverse(LQ, LK).Multiply(LM.Add(LX.Multiply(LR))); + // k leaks x through s, so the exponent is blinded with a random multiple of q before the + // variable-time ModPow; g has order q, so r is unchanged + LBlindedK := TBigIntegerUtilities.CreateBlindedExponent(LK, LQ, FRandom); + LR := LParameters.G.ModPow(LBlindedK, LParameters.P).&Mod(LQ); - LS := LK.&Mod(LQ); + // s = k^-1 * (m + x * r) mod q, keeping secret x and k^-1 off BigInteger.Mod, whose cost follows the quotient + LS := TBigIntegerUtilities.ModMult(LQ, TBigIntegerUtilities.ModOddInverse(LQ, LK), + TBigIntegerUtilities.ModAdd(LQ, LM, TBigIntegerUtilities.ModMult(LQ, LX, LR))); Result := TCryptoLibGenericArray.Create(LR, LS); end; @@ -188,7 +192,8 @@ procedure TDsaSigner.Init(AForSigning: Boolean; end; FKey := LParameters as IDsaPrivateKeyParameters; - FRandom := InitSecureRandom(not FKCalculator.IsDeterministic, LProvidedRandom); + // needed even for a deterministic k: signing blinds the exponent + FRandom := InitSecureRandom(True, LProvidedRandom); end else begin diff --git a/CryptoLib/src/Crypto/Signers/ClpECDsaSigner.pas b/CryptoLib/src/Crypto/Signers/ClpECDsaSigner.pas index 231a5ecb..45393b58 100644 --- a/CryptoLib/src/Crypto/Signers/ClpECDsaSigner.pas +++ b/CryptoLib/src/Crypto/Signers/ClpECDsaSigner.pas @@ -189,7 +189,8 @@ function TECDsaSigner.GenerateSignature(const AMessage: TCryptoLibByteArray) begin LEC := FKey.Parameters; LN := LEC.N; - LE := CalculateE(LN, AMessage); + // e is public, and CalculateE can leave it at or past n, which ModAdd below rejects rather than reduces + LE := CalculateE(LN, AMessage).&Mod(LN); LD := (FKey as IECPrivateKeyParameters).D; // constant-time, allocation-free nonce math when available for this order LHaveScalarOps := TScalarFieldRegistry.TryGet(LN, LScalarOps); @@ -220,7 +221,9 @@ function TECDsaSigner.GenerateSignature(const AMessage: TCryptoLibByteArray) if LHaveScalarOps then LS := LScalarOps.ComputeS(LK, LE, LD, LR) else - LS := TBigIntegerUtilities.ModOddInverse(LN, LK).Multiply(LE.Add(LD.Multiply(LR))).&Mod(LN); + // s = k^-1 * (e + d * r) mod n, keeping secret d and k^-1 off BigInteger.Mod, whose cost follows the quotient + LS := TBigIntegerUtilities.ModMult(LN, TBigIntegerUtilities.ModOddInverse(LN, LK), + TBigIntegerUtilities.ModAdd(LN, LE, TBigIntegerUtilities.ModMult(LN, LD, LR))); until (not(LS.SignValue = 0)); diff --git a/CryptoLib/src/Crypto/Signers/ClpECNRSigner.pas b/CryptoLib/src/Crypto/Signers/ClpECNRSigner.pas index fdb6cc9c..e6746a19 100644 --- a/CryptoLib/src/Crypto/Signers/ClpECNRSigner.pas +++ b/CryptoLib/src/Crypto/Signers/ClpECNRSigner.pas @@ -233,8 +233,8 @@ function TECNRSigner.GenerateSignature(const AMessage: TCryptoLibByteArray) // generate s LX := LPrivKey.D; // private key value LU := (LTempPair.Private as IECPrivateKeyParameters).D; - // temp's private key value - LS := LU.Subtract(LR.Multiply(LX)).&Mod(LN); + // temp's private key value, keeping secret x and u off BigInteger.Mod, whose cost follows the quotient + LS := TBigIntegerUtilities.ModSubtract(LN, LU, TBigIntegerUtilities.ModMult(LN, LR, LX)); Result := TCryptoLibGenericArray.Create(LR, LS); end; diff --git a/CryptoLib/src/Math/BinPoly/ClpBinPolyScalarBackend.pas b/CryptoLib/src/Math/BinPoly/ClpBinPolyScalarBackend.pas index 464035f3..586a2ab7 100644 --- a/CryptoLib/src/Math/BinPoly/ClpBinPolyScalarBackend.pas +++ b/CryptoLib/src/Math/BinPoly/ClpBinPolyScalarBackend.pas @@ -60,6 +60,7 @@ TBinPolyScalarBackend = class sealed implementation uses + ClpArrayUtilities, ClpBinPolyScalarMedium, ClpBinPolyScalarLarge; @@ -90,10 +91,15 @@ class procedure TBinPolyScalarBackend.ImplMul(ALen: Int32; const AX: TCryptoLibU SetLength(LU, 16); - for LI := 0 to ALen - 1 do - ImplMulwAccTable(LU, AX[AXOff + LI], AY[AYOff + LI], AZz, AZzOff + (LI shl 1)); + // the table holds multiples of operand limbs, so wipe it after use + try + for LI := 0 to ALen - 1 do + ImplMulwAccTable(LU, AX[AXOff + LI], AY[AYOff + LI], AZz, AZzOff + (LI shl 1)); - ImplMulPostprocess(ALen, AX, AXOff, AY, AYOff, AZz, AZzOff, LU); + ImplMulPostprocess(ALen, AX, AXOff, AY, AYOff, AZz, AZzOff, LU); + finally + TArrayUtilities.Fill(LU, 0, System.Length(LU), UInt64(0)); + end; end; class procedure TBinPolyScalarBackend.ImplMulPostprocess(ALen: Int32; const AX: TCryptoLibUInt64Array; AXOff: Int32; diff --git a/CryptoLib/src/Math/ClpBigInteger.pas b/CryptoLib/src/Math/ClpBigInteger.pas index 932e0dc1..7ff3dcb9 100644 --- a/CryptoLib/src/Math/ClpBigInteger.pas +++ b/CryptoLib/src/Math/ClpBigInteger.pas @@ -102,6 +102,9 @@ TBigInteger = record function GetBitLength: Int32; function GetBitCount: Int32; function ModInversePow2(const AM: TBigInteger): TBigInteger; + // z = d^-1 mod 2^pow for odd d (Hensel lifting), a word at a time. + class procedure InversePow2(APow, ALen: Int32; const AD: TCryptoLibUInt32Array; + ADLen: Int32; const AAcc, AZ: TCryptoLibUInt32Array); static; class function ModPowBarrett(const AB, AE, AM: TBigInteger): TBigInteger; static; class function ReduceBarrett(const AX, AM, AMr, AYu: TBigInteger): TBigInteger; static; class function ModPowMonty(const AB, AE, AM: TBigInteger; const AConvert: Boolean; @@ -321,6 +324,7 @@ implementation uses ClpMod, + ClpNat, ClpGatherKernelSimd, ClpMontKernelContext, ClpSecureRandom; @@ -3855,9 +3859,10 @@ class function TBigInteger.ExtEuclid(const AA, AB: TBigInteger; out AU1Out: TBig function TBigInteger.ModInversePow2(const AM: TBigInteger): TBigInteger; var - LPow, LBitsCorrect: Int32; + LPow, LLen, LDLen: Int32; LInv64: Int64; - LX, LD, LT: TBigInteger; + LX, LD: TBigInteger; + LDd, LAcc, LZ: TCryptoLibUInt32Array; begin {$IFDEF DEBUG} System.Assert(AM.FSign > 0); @@ -3866,25 +3871,57 @@ function TBigInteger.ModInversePow2(const AM: TBigInteger): TBigInteger; if not TestBit(0) then raise EArithmeticCryptoLibException.CreateRes(@SNumbersNotRelativelyPrime); LPow := AM.BitLength - 1; - LInv64 := Int64(TMod.Inverse64(UInt64(Int64Value))); - if LPow < 64 then - begin - LInv64 := LInv64 and ((Int64(1) shl LPow) - 1); - end; - LX := ValueOf(LInv64); - if LPow > 64 then + + if LPow <= 64 then begin - LD := Remainder(AM); - LBitsCorrect := 64; - repeat - LT := LX.Multiply(LD).Remainder(AM); - LX := LX.Multiply(FTwo.Subtract(LT)).Remainder(AM); - LBitsCorrect := LBitsCorrect shl 1; - until LBitsCorrect >= LPow; + LInv64 := Int64(TMod.Inverse64(UInt64(Int64Value))); + if LPow < 64 then + LInv64 := LInv64 and ((Int64(1) shl LPow) - 1); + LX := ValueOf(LInv64); + if LX.FSign < 0 then + LX := LX.Add(AM); + Result := LX; + Exit; end; - if LX.FSign < 0 then - LX := LX.Add(AM); - Result := LX; + + if (FSign < 0) or (BitLength > LPow) then + LD := &Mod(AM) + else + LD := Self; + + LLen := TNat.GetLengthForBits(LPow); + LDLen := TNat.GetLengthForBits(LD.BitLength); + LDd := TNat.FromBigInteger(LPow, LD); + LAcc := TNat.Create(LLen); + LZ := TNat.Create(LLen); + InversePow2(LPow, LLen, LDd, LDLen, LAcc, LZ); + Result := TNat.ToBigInteger(LLen, LZ); +end; + +class procedure TBigInteger.InversePow2(APow, ALen: Int32; const AD: TCryptoLibUInt32Array; + ADLen: Int32; const AAcc, AZ: TCryptoLibUInt32Array); +var + LDInv, LTarget, LZi, LC: UInt32; + LI, LN: Int32; +begin + // acc (initially zero) holds d * z; each word of z brings the matching word of acc to that of 1. Before step i + // d * z spans at most i + dLen words, so the carry lands in a still-zero word. + LDInv := TMod.Inverse32(AD[0]); + LTarget := 1; + for LI := 0 to ALen - 1 do + begin + LZi := UInt32((LTarget - AAcc[LI]) * LDInv); + AZ[LI] := LZi; + LTarget := 0; + + LN := ADLen; + if (ALen - LI) < LN then + LN := ALen - LI; + LC := TNat.MulWordAddTo(LN, LZi, AD, 0, AAcc, LI); + if (LI + LN) < ALen then + AAcc[LI + LN] := LC; + end; + AZ[ALen - 1] := AZ[ALen - 1] and (UInt32($FFFFFFFF) shr ((-APow) and 31)); end; class function TBigInteger.ReduceBarrett(const AX, AM, AMr, AYu: TBigInteger): TBigInteger; diff --git a/CryptoLib/src/Math/ClpBigIntegerUtilities.pas b/CryptoLib/src/Math/ClpBigIntegerUtilities.pas index c33b37a4..18d65773 100644 --- a/CryptoLib/src/Math/ClpBigIntegerUtilities.pas +++ b/CryptoLib/src/Math/ClpBigIntegerUtilities.pas @@ -36,8 +36,10 @@ interface SStandardLengthExceeded = 'standard length exceeded'; SMinMayNotBeGreaterThanMax = 'min may not be greater than max'; SMustBeOdd = 'must be odd'; + SMustBePositive = 'must be positive'; SModulusNotPositive = 'BigInteger: modulus not positive'; SBigIntegerNotInvertible = 'BigInteger not invertible'; + SModOperandsOutOfRange = '''X'' and ''Y'' must be in the range [0, M)'; type /// @@ -71,6 +73,13 @@ TBigIntegerUtilities = class sealed(TObject) class function GetZero: TBigInteger; static; class function GetOne: TBigInteger; static; + class procedure CheckModOperands(const AM, AX, AY: TBigInteger); static; + // z = x * y * R^-1 mod m, for R = 2^(32 * len), x and y in [0, m); z may alias x or y. + class procedure MontgomeryMultiply(ALen: Int32; const AX, AY, AM: TCryptoLibUInt32Array; + AMDash: UInt32; const AT, AZ: TCryptoLibUInt32Array); static; + // modular inverse of X mod M (M odd); returns False (no raise) when X is not invertible. + class function ImplModOddInverse(const AM, AX: TBigInteger; out AResult: TBigInteger): Boolean; static; + public /// /// Gets the BigInteger equality comparer for use with TDictionary. @@ -201,6 +210,39 @@ TBigIntegerUtilities = class sealed(TObject) /// the value to check. /// whether is coprime or not. class function ModOddIsCoprimeVar(const AM, AX: TBigInteger): Boolean; static; + + /// + /// (X + Y) mod M, for X and Y already in [0, M), in time independent of the values. Operands outside + /// [0, M) are rejected rather than reduced. + /// + class function ModAdd(const AM, AX, AY: TBigInteger): TBigInteger; static; + + /// + /// (X - Y) mod M, for X and Y already in [0, M), in time independent of the values. Operands outside + /// [0, M) are rejected rather than reduced. + /// + class function ModSubtract(const AM, AX, AY: TBigInteger): TBigInteger; static; + + /// + /// (X * Y) mod M, for odd M and X, Y already in [0, M), in time independent of the values (Montgomery + /// multiplication). Operands outside [0, M) are rejected rather than reduced. + /// + class function ModMult(const AM, AX, AY: TBigInteger): TBigInteger; static; + + /// + /// X^E mod M for odd prime M and X in [1, M), with the base blinded so a chosen X cannot steer the timing. + /// For a fresh random v this computes (X * v)^E * (v^-1)^E; neither exponentiation sees a base the caller + /// knows. The exponent is not randomized. Costs two exponentiations and an inversion. + /// + class function ModPowBaseBlinded(const AM, AX, AE: TBigInteger; + const ARandom: ISecureRandom): TBigInteger; static; + + /// + /// Returns an exponent congruent to AExponent modulo the group order, blinded by a random multiple of + /// AGroupOrder, so a fixed secret exponent does not drive the timing of a following variable-time ModPow. + /// + class function CreateBlindedExponent(const AExponent, AGroupOrder: TBigInteger; + const ARandom: ISecureRandom): TBigInteger; static; end; implementation @@ -392,7 +434,7 @@ class procedure TBigIntegerUtilities.WriteUnsignedByteArray(const AOutStr: TStre AOutStr.Write(LBuffer[0], System.Length(LBuffer)); end; -class function TBigIntegerUtilities.ModOddInverse(const AM, AX: TBigInteger): TBigInteger; +class function TBigIntegerUtilities.ImplModOddInverse(const AM, AX: TBigInteger; out AResult: TBigInteger): Boolean; var LBits, LLen: Int32; LReducedX: TBigInteger; @@ -415,9 +457,16 @@ class function TBigIntegerUtilities.ModOddInverse(const AM, AX: TBigInteger): TB LZ := TNat.Create(LLen); if TMod.ModOddInverse(LM, LX, LZ) = 0 then - raise EArithmeticCryptoLibException.CreateRes(@SBigIntegerNotInvertible); + Exit(False); - Result := TNat.ToBigInteger(LLen, LZ); + AResult := TNat.ToBigInteger(LLen, LZ); + Result := True; +end; + +class function TBigIntegerUtilities.ModOddInverse(const AM, AX: TBigInteger): TBigInteger; +begin + if not ImplModOddInverse(AM, AX, Result) then + raise EArithmeticCryptoLibException.CreateRes(@SBigIntegerNotInvertible); end; class function TBigIntegerUtilities.ModOddInverseVar(const AM, AX: TBigInteger): TBigInteger; @@ -512,4 +561,145 @@ class function TBigIntegerUtilities.ModOddIsCoprimeVar(const AM, AX: TBigInteger Result := TMod.ModOddIsCoprimeVar(LM, LX); end; +class procedure TBigIntegerUtilities.CheckModOperands(const AM, AX, AY: TBigInteger); +begin + if AM.SignValue <> 1 then + raise EArithmeticCryptoLibException.CreateRes(@SModulusNotPositive); + if (AX.SignValue < 0) or (AX.CompareTo(AM) >= 0) or (AY.SignValue < 0) or (AY.CompareTo(AM) >= 0) then + raise EArgumentCryptoLibException.CreateRes(@SModOperandsOutOfRange); +end; + +class function TBigIntegerUtilities.ModAdd(const AM, AX, AY: TBigInteger): TBigInteger; +var + LBits, LLen, LBorrow: Int32; + LM, LX, LY: TCryptoLibUInt32Array; +begin + CheckModOperands(AM, AX, AY); + + // the extra bit of width means X + Y, below 2M, cannot carry out of the top word, so one conditional + // subtraction of M reduces it + LBits := AM.BitLength + 1; + LM := TNat.FromBigInteger(LBits, AM); + LX := TNat.FromBigInteger(LBits, AX); + LY := TNat.FromBigInteger(LBits, AY); + LLen := System.Length(LM); + + TNat.Add(LLen, LX, LY, LX); + LBorrow := TNat.Sub(LLen, LX, LM, LY); // Y = X - M; borrow is -1 exactly when X < M + TNat.CMov(LLen, not LBorrow, LY, 0, LX, 0); // keep X - M unless the subtraction went negative + Result := TNat.ToBigInteger(LLen, LX); +end; + +class function TBigIntegerUtilities.ModSubtract(const AM, AX, AY: TBigInteger): TBigInteger; +var + LBits, LLen, LBorrow: Int32; + LM, LX, LY: TCryptoLibUInt32Array; +begin + CheckModOperands(AM, AX, AY); + + // X - Y lies in (-M, M), so one conditional addition of M reduces it; the width is that of ModAdd + LBits := AM.BitLength + 1; + LM := TNat.FromBigInteger(LBits, AM); + LX := TNat.FromBigInteger(LBits, AX); + LY := TNat.FromBigInteger(LBits, AY); + LLen := System.Length(LM); + + LBorrow := TNat.Sub(LLen, LX, LY, LX); // borrow is -1 exactly when X < Y + TNat.Add(LLen, LX, LM, LY); // Y = X + M, discarding the carry off the top + TNat.CMov(LLen, LBorrow, LY, 0, LX, 0); // take X + M only where the difference went negative + Result := TNat.ToBigInteger(LLen, LX); +end; + +class procedure TBigIntegerUtilities.MontgomeryMultiply(ALen: Int32; const AX, AY, AM: TCryptoLibUInt32Array; + AMDash: UInt32; const AT, AZ: TCryptoLibUInt32Array); +var + LI, LBorrow, LTopSet: Int32; + LC: UInt64; + LTop: UInt32; +begin + TArrayUtilities.Fill(AT, 0, System.Length(AT), UInt32(0)); + + for LI := 0 to ALen - 1 do + begin + // the window AT[LI..LI+ALen+1]: its top word has not been written yet, so it is zero + LC := UInt64(TNat.MulWordAddTo(ALen, AY[LI], AX, 0, AT, LI)) + AT[LI + ALen]; + AT[LI + ALen] := UInt32(LC); + AT[LI + ALen + 1] := UInt32(LC shr 32); + + LC := UInt64(TNat.MulWordAddTo(ALen, UInt32(AT[LI] * AMDash), AM, 0, AT, LI)) + AT[LI + ALen]; + AT[LI + ALen] := UInt32(LC); + AT[LI + ALen + 1] := AT[LI + ALen + 1] + UInt32(LC shr 32); + end; + + // the result, below 2m, is in AT[ALen..2*ALen]: subtract m unless it is already below m, which is when the + // subtraction goes negative and the top word is clear + LTop := AT[2 * ALen]; + LBorrow := TNat.Sub(ALen, AT, ALen, AM, 0, AZ, 0); + LTopSet := Int32((LTop or (UInt32(0) - LTop)) shr 31); + TNat.CMov(ALen, LBorrow and (LTopSet - 1), AT, ALen, AZ, 0); +end; + +class function TBigIntegerUtilities.ModMult(const AM, AX, AY: TBigInteger): TBigInteger; +var + LBits, LLen: Int32; + LMDash: UInt32; + LR2: TBigInteger; + LM, LX, LY, LR2Words, LT: TCryptoLibUInt32Array; +begin + if not AM.TestBit(0) then + raise EArgumentCryptoLibException.CreateRes(@SMustBeOdd); + + CheckModOperands(AM, AX, AY); + + LBits := AM.BitLength; + LLen := TNat.GetLengthForBits(LBits); + + // R = 2^(32 * len) exceeds the odd M, so they are coprime. R^2 mod M depends only on the public modulus. + LR2 := One.ShiftLeft(LLen shl 6).&Mod(AM); + + LM := TNat.FromBigInteger(LBits, AM); + LX := TNat.FromBigInteger(LBits, AX); + LY := TNat.FromBigInteger(LBits, AY); + LR2Words := TNat.FromBigInteger(LBits, LR2); + LT := TNat.Create(2 * LLen + 1); + LMDash := UInt32(0 - Int64(TMod.Inverse32(LM[0]))); + + // the first product leaves X * Y * R^-1, the second multiplies by R^2 * R^-1 to undo it + MontgomeryMultiply(LLen, LX, LY, LM, LMDash, LT, LX); + MontgomeryMultiply(LLen, LX, LR2Words, LM, LMDash, LT, LX); + Result := TNat.ToBigInteger(LLen, LX); +end; + +class function TBigIntegerUtilities.ModPowBaseBlinded(const AM, AX, AE: TBigInteger; + const ARandom: ISecureRandom): TBigInteger; +var + LMaxV, LV, LVInv, LBlinded, LUnblind: TBigInteger; +begin + // zero cannot be blinded (the product with v stays zero), and ModMult below rejects X >= M + if AX.SignValue <= 0 then + raise EArgumentCryptoLibException.CreateRes(@SMustBePositive); + + // the blinding is only as good as v is secret, so v stays on the fixed-time helpers. For a prime M the + // first v is always invertible; a v sharing a factor with a composite M is redrawn. + LMaxV := AM.Subtract(TBigInteger.Two); + repeat + LV := CreateRandomInRange(TBigInteger.Two, LMaxV, ARandom); + until ImplModOddInverse(AM, LV, LVInv); + + LBlinded := ModMult(AM, AX, LV).ModPow(AE, AM); + LUnblind := LVInv.ModPow(AE, AM); + Result := ModMult(AM, LBlinded, LUnblind); +end; + +class function TBigIntegerUtilities.CreateBlindedExponent(const AExponent, AGroupOrder: TBigInteger; + const ARandom: ISecureRandom): TBigInteger; +const + RandomBits = Int32(7); +var + LBlind: TBigInteger; +begin + LBlind := CreateRandomBigInteger(RandomBits, ARandom).SetBit(RandomBits); + Result := AExponent.Add(LBlind.Multiply(AGroupOrder)); +end; + end. diff --git a/CryptoLib/src/Misc/ClpCryptoLibConfig.pas b/CryptoLib/src/Misc/ClpCryptoLibConfig.pas index 92822e83..b19fb17b 100644 --- a/CryptoLib/src/Misc/ClpCryptoLibConfig.pas +++ b/CryptoLib/src/Misc/ClpCryptoLibConfig.pas @@ -215,9 +215,12 @@ TDHConfig = class sealed(TObject) class var FMaxSize: TNullable; + FAllowShortPrivateValue: Boolean; class function GetMaxSize: Int32; static; class procedure SetMaxSize(AValue: Int32); static; + class function GetAllowShortPrivateValue: Boolean; static; + class procedure SetAllowShortPrivateValue(AValue: Boolean); static; public /// Restores this area's settings to their defaults. @@ -228,6 +231,13 @@ TDHConfig = class sealed(TObject) /// than one raises; call to go back to the default. /// class property MaxSize: Int32 read GetMaxSize write SetMaxSize; + + /// + /// When set, a DH private value length below twice the security strength of p (the SP 800-56A floor) + /// is accepted instead of rejected. Off by default. + /// + class property AllowShortPrivateValue: Boolean read GetAllowShortPrivateValue + write SetAllowShortPrivateValue; end; /// Class reference, so the settings are reachable without an instance. @@ -713,6 +723,7 @@ class procedure TX509Config.SetAllowEmptyIssuerCert(AValue: Boolean); class procedure TDHConfig.ResetToDefaults(); begin FMaxSize := TNullable.None; + FAllowShortPrivateValue := False; end; class function TDHConfig.GetMaxSize: Int32; @@ -732,6 +743,16 @@ class procedure TDHConfig.SetMaxSize(AValue: Int32); FMaxSize := TNullable.Some(AValue); end; +class function TDHConfig.GetAllowShortPrivateValue: Boolean; +begin + Result := FAllowShortPrivateValue; +end; + +class procedure TDHConfig.SetAllowShortPrivateValue(AValue: Boolean); +begin + FAllowShortPrivateValue := AValue; +end; + { TDsaConfig } class procedure TDsaConfig.ResetToDefaults(); diff --git a/CryptoLib/src/OpenSsl/ClpOpenSslMiscPemGenerator.pas b/CryptoLib/src/OpenSsl/ClpOpenSslMiscPemGenerator.pas index d835dc63..bec4c244 100644 --- a/CryptoLib/src/OpenSsl/ClpOpenSslMiscPemGenerator.pas +++ b/CryptoLib/src/OpenSsl/ClpOpenSslMiscPemGenerator.pas @@ -124,6 +124,9 @@ constructor TOpenSslMiscPemGenerator.Create(const AObj: TValue; const AAlgorithm function TOpenSslMiscPemGenerator.Generate: IPemObject; begin + // an algorithm with a nil password would otherwise be treated as an empty password + if (FAlgorithm <> '') and (FPassword = nil) then + raise EArgumentNilCryptoLibException.CreateRes(@SPasswordNil); try if (FAlgorithm <> '') then Result := CreatePemObjectEncrypted(FObj, FAlgorithm, FPassword, FRandom) From 9799c123f614c5b1c4d33ca1e4940c6a67d1df44 Mon Sep 17 00:00:00 2001 From: Ugochukwu Mmaduekwe Date: Tue, 24 Nov 2026 11:23:17 +0100 Subject: [PATCH 2/2] Bind the re-validated DH public key to an interface so it is freed When a DH agreement re-validates a subclassed peer public key, the freshly constructed TDHPublicKeyParameters was read through a property on the constructor result without being assigned to an interface, so its reference count stayed at zero and the instance was never released. Bind it to an interface local first, then read Y from that. Covers both DHBasicAgreement and DHAgreement. --- CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas | 7 +++++-- CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas b/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas index fb74836e..d4f28a9c 100644 --- a/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas +++ b/CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas @@ -100,7 +100,7 @@ function TDHAgreement.CalculateAgreement(const APub: IDHPublicKeyParameters; const AMessage: TBigInteger): TBigInteger; var LP, LPeerY, LPeerMessage, LStaticPart: TBigInteger; - LParameter: IDHPublicKeyParameters; + LParameter, LReValidated: IDHPublicKeyParameters; LPubConcrete: TDHPublicKeyParameters; begin if (APub = nil) then @@ -129,7 +129,10 @@ function TDHAgreement.CalculateAgreement(const APub: IDHPublicKeyParameters; if LPubConcrete.ClassType = TDHPublicKeyParameters then LPeerY := APub.Y else - LPeerY := TDHPublicKeyParameters.Create(APub.Y, FDhParams).Y; + begin + LReValidated := TDHPublicKeyParameters.Create(APub.Y, FDhParams) as IDHPublicKeyParameters; + LPeerY := LReValidated.Y; + end; // our ephemeral value is used once, so nothing accumulates against it and this exponentiation is left as it is Result := LPeerY.ModPow(FPrivateValue, LP); diff --git a/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas b/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas index 9122edec..c636b748 100644 --- a/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas +++ b/CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas @@ -87,7 +87,7 @@ implementation function TDHBasicAgreement.CalculateAgreement(const APubKey: ICipherParameters) : TBigInteger; var - LPub: IDHPublicKeyParameters; + LPub, LReValidated: IDHPublicKeyParameters; LPubConcrete: TDHPublicKeyParameters; LP, LPeerY: TBigInteger; begin @@ -109,7 +109,10 @@ function TDHBasicAgreement.CalculateAgreement(const APubKey: ICipherParameters) if LPubConcrete.ClassType = TDHPublicKeyParameters then LPeerY := LPub.Y else - LPeerY := TDHPublicKeyParameters.Create(LPub.Y, FDhParams).Y; + begin + LReValidated := TDHPublicKeyParameters.Create(LPub.Y, FDhParams) as IDHPublicKeyParameters; + LPeerY := LReValidated.Y; + end; // the exponent is our private value, long lived for static-static agreement, and the peer chooses the base, // so blind the base: the variable-time ModPow's timing could otherwise be accumulated against the key