Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions CryptoLib.Tests/src/Crypto/DHTests.pas
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ interface
ClpIX9DHAsn1Objects,
ClpX9DHAsn1Objects,
ClpBigInteger,
ClpCryptoLibConfig,
ClpCryptoLibTypes,
ClpCryptoLibExceptions,
CryptoLibTestBase;
Expand Down Expand Up @@ -142,6 +143,7 @@ TTestDH = class(TCryptoLibAlgorithmTestCase)
procedure TestDHSubgroupConfinement;
procedure TestModulusSizeBound;
procedure TestDHBounds;
procedure TestPrivateValueLengthFloor;
procedure TestDHPgenCounterBound;
procedure TestDHMaliciousMessage;
end;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -693,14 +696,42 @@ 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
Fail('Generated secrets with weak public key');
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
Expand Down
33 changes: 33 additions & 0 deletions CryptoLib.Tests/src/Crypto/DSATests.pas
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ TTestDSA = class(TCryptoLibAlgorithmTestCase)
procedure TestDsa2Parameters;
procedure TestKeyGenerationAll;
procedure TestParameters;
procedure TestPrivateKeyRange;
procedure TestModulusSizeBound;

/// <summary>
Expand Down Expand Up @@ -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
Expand Down
44 changes: 44 additions & 0 deletions CryptoLib.Tests/src/Math/BigIntegerTests.pas
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ interface
ClpSecureRandom,
ClpISecureRandom,
ClpBigInteger,
ClpBigIntegerUtilities,
ClpCryptoLibTypes,
ClpCryptoLibExceptions,
CryptoLibTestBase;
Expand Down Expand Up @@ -104,6 +105,7 @@ TTestBigInteger = class(TCryptoLibAlgorithmTestCase)
procedure TestToString();
procedure TestValueOf();
procedure TestXor();
procedure TestModArithmeticAndBlinding();
end;

implementation
Expand Down Expand Up @@ -1495,6 +1497,48 @@ procedure TTestBigInteger.TestXor;
end;
end;

procedure TTestBigInteger.TestModArithmeticAndBlinding();
var
LM, LX, LY, LE: TBigInteger;
LModuli: TCryptoLibGenericArray<TBigInteger>;
LI, LJ: Int32;
LRaised: Boolean;
begin
// small odd primes and the secp256r1 field prime
LModuli := TCryptoLibGenericArray<TBigInteger>.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
Expand Down
27 changes: 27 additions & 0 deletions CryptoLib.Tests/src/OpenSsl/OpenSslWriterTests.pas
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ interface
ClpIPemObject,
ClpIOpenSslPemWriter,
ClpOpenSslPemWriter,
ClpCryptoLibExceptions,
ClpIOpenSslPemReader,
ClpOpenSslPemReader,
ClpIOpenSslPasswordFinder,
Expand Down Expand Up @@ -87,6 +88,7 @@ TOpenSslWriterTest = class(TCryptoLibAlgorithmTestCase)
procedure TestWriteReadEcKeyGenerated;
procedure TestWritePemObjectOverride;
procedure TestEncryptedWriteRead;
procedure TestEncryptedWriteNilPasswordRejected;
end;

implementation
Expand Down Expand Up @@ -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<IAsymmetricKeyParameter>(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}
Expand Down
16 changes: 12 additions & 4 deletions CryptoLib/src/Crypto/Agreements/ClpDHAgreement.pas
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ interface
uses
SysUtils,
ClpBigInteger,
ClpBigIntegerUtilities,
ClpISecureRandom,
ClpCryptoServicesRegistrar,
ClpICipherParameters,
Expand Down Expand Up @@ -98,8 +99,8 @@ implementation
function TDHAgreement.CalculateAgreement(const APub: IDHPublicKeyParameters;
const AMessage: TBigInteger): TBigInteger;
var
LP, LPeerY, LPeerMessage: TBigInteger;
LParameter: IDHPublicKeyParameters;
LP, LPeerY, LPeerMessage, LStaticPart: TBigInteger;
LParameter, LReValidated: IDHPublicKeyParameters;
LPubConcrete: TDHPublicKeyParameters;
begin
if (APub = nil) then
Expand Down Expand Up @@ -128,14 +129,21 @@ 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);

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;
Expand Down
39 changes: 29 additions & 10 deletions CryptoLib/src/Crypto/Agreements/ClpDHBasicAgreement.pas
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ interface
uses
SysUtils,
ClpBigInteger,
ClpBigIntegerUtilities,
ClpISecureRandom,
ClpCryptoServicesRegistrar,
ClpICipherParameters,
ClpIBasicAgreement,
ClpIDHBasicAgreement,
ClpIDHParameters,
ClpDHParameters,
ClpIParametersWithRandom,
ClpCryptoLibExceptions;

Expand All @@ -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
/// <summary>
Expand All @@ -56,6 +59,7 @@ TDHBasicAgreement = class(TInterfacedObject, IDHBasicAgreement,
var
FKey: IDHPrivateKeyParameters;
FDhParams: IDHParameters;
FRandom: ISecureRandom;

public
/// <summary>
Expand Down Expand Up @@ -83,7 +87,8 @@ implementation
function TDHBasicAgreement.CalculateAgreement(const APubKey: ICipherParameters)
: TBigInteger;
var
LPub: IDHPublicKeyParameters;
LPub, LReValidated: IDHPublicKeyParameters;
LPubConcrete: TDHPublicKeyParameters;
LP, LPeerY: TBigInteger;
begin
if (FKey = nil) then
Expand All @@ -98,13 +103,20 @@ function TDHBasicAgreement.CalculateAgreement(const APubKey: ICipherParameters)

LP := FDhParams.P;

LPeerY := LPub.Y;

if ((not LPeerY.IsInitialized) or (LPeerY.CompareTo(TBigInteger.One) <= 0) or
(LPeerY.CompareTo(LP.Subtract(TBigInteger.One)) >= 0)) then
raise EArgumentCryptoLibException.CreateRes(@SDHPublicKeyWeak);
// 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
begin
LReValidated := TDHPublicKeyParameters.Create(LPub.Y, FDhParams) as IDHPublicKeyParameters;
LPeerY := LReValidated.Y;
end;

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);
Expand All @@ -121,9 +133,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);
Expand Down
8 changes: 4 additions & 4 deletions CryptoLib/src/Crypto/Generators/ClpDHGenerators.pas
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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;
Expand Down
Loading
Loading