From 155e93d4024e6d31a844b964291f7184fc7c0f3d Mon Sep 17 00:00:00 2001 From: Ugochukwu Mmaduekwe Date: Wed, 28 Oct 2026 23:28:32 +0100 Subject: [PATCH] Accept negative ENUMERATED values, make PKCS12 write iterations configurable, and wipe transient key material DerEnumerated now accepts negative values per X.690 signed-integer encoding and gains TryGetIntValueExact. Asn1Dumper gains AppendAsString overloads so callers can build into an existing buffer. The HMAC k-calculator wipes the private scalar bytes after seeding. PKCS12 write-side iteration counts are driven by a configurable StoreIterationCount. Adds ML-DSA and SLH-DSA component encoding-length tests and a negative-ENUMERATED round-trip test. --- CryptoLib.Tests/src/Asn1/EnumeratedTests.pas | 22 +++++ CryptoLib.Tests/src/Crypto/MlDsaTests.pas | 80 +++++++++++++++++++ CryptoLib.Tests/src/Crypto/SlhDsaTests.pas | 70 ++++++++++++++++ CryptoLib.Tests/src/Pkcs/Pkcs12StoreTests.pas | 9 +++ CryptoLib/src/Asn1/ClpAsn1Dumper.pas | 19 ++++- CryptoLib/src/Asn1/ClpAsn1Objects.pas | 31 ++++--- .../ClpHMacDsaKCalculator.pas | 4 + .../src/Interfaces/Asn1/ClpIAsn1Objects.pas | 2 + CryptoLib/src/Misc/ClpCryptoLibConfig.pas | 29 +++++++ CryptoLib/src/Pkcs/ClpPkcs12Store.pas | 20 ++++- CryptoLib/src/Pkcs/ClpPkcs12StoreBuilder.pas | 8 +- CryptoLib/src/X509/ClpX509Certificate.pas | 3 +- 12 files changed, 274 insertions(+), 23 deletions(-) diff --git a/CryptoLib.Tests/src/Asn1/EnumeratedTests.pas b/CryptoLib.Tests/src/Asn1/EnumeratedTests.pas index 02fe0f11..b1b4a0e8 100644 --- a/CryptoLib.Tests/src/Asn1/EnumeratedTests.pas +++ b/CryptoLib.Tests/src/Asn1/EnumeratedTests.pas @@ -31,6 +31,7 @@ interface TestFramework, {$ENDIF FPC} ClpAsn1Core, + ClpAsn1Objects, ClpIAsn1Objects, ClpIAsn1Core, ClpCryptoLibTypes, @@ -75,6 +76,10 @@ TEnumeratedTest = class(TCryptoLibAlgorithmTestCase) /// Makes sure multiple identically sized values are parsed correctly. /// procedure TestReadingMultipleTripleByteItems; + /// + /// An ENUMERATED is encoded like an INTEGER, so a negative value is valid and must round-trip. + /// + procedure TestNegativeValueRoundTrips; end; @@ -182,6 +187,23 @@ procedure TEnumeratedTest.TestReadingMultipleTripleByteItems; CheckEquals('1.3.6.1', LObjectId.Id, 'Unexpected OBJECT IDENTIFIER value'); end; +procedure TEnumeratedTest.TestNegativeValueRoundTrips; +var + LEnum, LDecoded: IDerEnumerated; + LEncoded: TCryptoLibByteArray; + LValue: Int32; +begin + LEnum := TDerEnumerated.Create(Int32(-1)) as IDerEnumerated; + CheckEquals(-1, LEnum.IntValueExact, 'a negative ENUMERATED keeps its value'); + + LEncoded := LEnum.GetEncoded(); + LDecoded := TDerEnumerated.GetInstance(LEncoded); + CheckEquals(-1, LDecoded.IntValueExact, 'a negative ENUMERATED round-trips through DER'); + + CheckTrue(LDecoded.TryGetIntValueExact(LValue), 'TryGetIntValueExact succeeds for an in-range value'); + CheckEquals(-1, LValue, 'TryGetIntValueExact yields the value'); +end; + initialization {$IFDEF FPC} diff --git a/CryptoLib.Tests/src/Crypto/MlDsaTests.pas b/CryptoLib.Tests/src/Crypto/MlDsaTests.pas index 57a5f8fa..6a0f2d40 100644 --- a/CryptoLib.Tests/src/Crypto/MlDsaTests.pas +++ b/CryptoLib.Tests/src/Crypto/MlDsaTests.pas @@ -62,6 +62,7 @@ interface ClpISecureRandom, ClpSecureRandom, ClpCryptoLibTypes, + ClpCryptoLibExceptions, NistSecureRandom; type @@ -90,10 +91,15 @@ TTestMlDsa = class(TCryptoLibAlgorithmTestCase) // Run a vector file through AImpl. AParameters nil => derive per record. procedure RunParamVectors(const ARelativePath: string; AImpl: TMlDsaVectorImpl; const AParameters: IMlDsaParameters); + procedure ImplComponentEncodingLengths(const AParameters: IMlDsaParameters); + // AKind: 0 = private-key encoding, 1 = public-key encoding, 2 = seed + procedure ExpectBadLengthRejected(const AParameters: IMlDsaParameters; + const AValid: TCryptoLibByteArray; AKind: Int32); published procedure TestConsistency44; procedure TestConsistency65; procedure TestConsistency87; + procedure TestComponentEncodingLengths; procedure TestKeyGen; procedure TestKeyGenAcvp44; procedure TestKeyGenAcvp65; @@ -248,6 +254,80 @@ procedure TTestMlDsa.TestConsistency87; ImplConsistency(TMlDsaParameters.MlDsa87); end; +procedure TTestMlDsa.ExpectBadLengthRejected(const AParameters: IMlDsaParameters; + const AValid: TCryptoLibByteArray; AKind: Int32); + + procedure CheckOne(const ABuf: TCryptoLibByteArray); + var + LRaised: Boolean; + begin + LRaised := False; + try + case AKind of + 0: + TMlDsaPrivateKeyParameters.FromEncoding(AParameters, ABuf); + 1: + TMlDsaPublicKeyParameters.FromEncoding(AParameters, ABuf); + else + TMlDsaPrivateKeyParameters.FromSeed(AParameters, ABuf); + end; + except + on E: EArgumentCryptoLibException do + LRaised := True; + end; + CheckTrue(LRaised, 'a wrong-length ML-DSA component must be rejected'); + end; + +var + LBuf: TCryptoLibByteArray; +begin + LBuf := System.Copy(AValid); + System.SetLength(LBuf, System.Length(AValid) + 1); + CheckOne(LBuf); + + LBuf := System.Copy(AValid); + System.SetLength(LBuf, System.Length(AValid) - 1); + CheckOne(LBuf); +end; + +procedure TTestMlDsa.ImplComponentEncodingLengths(const AParameters: IMlDsaParameters); +var + LKpg: IAsymmetricCipherKeyPairGenerator; + LKp: IAsymmetricCipherKeyPair; + LPriv: IMlDsaPrivateKeyParameters; + LPub: IMlDsaPublicKeyParameters; + LPrivEnc, LPubEnc, LSeed: TCryptoLibByteArray; +begin + LKpg := TMlDsaKeyPairGenerator.Create; + LKpg.Init(TMlDsaKeyGenerationParameters.Create(FRandom, AParameters) as IKeyGenerationParameters); + LKp := LKpg.GenerateKeyPair(); + LPriv := LKp.Private as IMlDsaPrivateKeyParameters; + LPub := LKp.Public as IMlDsaPublicKeyParameters; + + LPrivEnc := LPriv.GetEncoded(); + LPubEnc := LPub.GetEncoded(); + LSeed := LPriv.GetSeed(); + + // correctly sized components round-trip + CheckNotNull(TMlDsaPrivateKeyParameters.FromEncoding(AParameters, LPrivEnc), + 'the private key encoding round-trips'); + CheckNotNull(TMlDsaPublicKeyParameters.FromEncoding(AParameters, LPubEnc), + 'the public key encoding round-trips'); + CheckNotNull(TMlDsaPrivateKeyParameters.FromSeed(AParameters, LSeed), 'the seed round-trips'); + + // a component one byte too long or too short is rejected + ExpectBadLengthRejected(AParameters, LPrivEnc, 0); + ExpectBadLengthRejected(AParameters, LPubEnc, 1); + ExpectBadLengthRejected(AParameters, LSeed, 2); +end; + +procedure TTestMlDsa.TestComponentEncodingLengths; +begin + ImplComponentEncodingLengths(TMlDsaParameters.MlDsa44); + ImplComponentEncodingLengths(TMlDsaParameters.MlDsa65); + ImplComponentEncodingLengths(TMlDsaParameters.MlDsa87); +end; + procedure TTestMlDsa.ImplKeyGen(const AName: string; const AData: TRspTxtRecord; const AParameters: IMlDsaParameters); var diff --git a/CryptoLib.Tests/src/Crypto/SlhDsaTests.pas b/CryptoLib.Tests/src/Crypto/SlhDsaTests.pas index 39e27dd0..bab8cc0f 100644 --- a/CryptoLib.Tests/src/Crypto/SlhDsaTests.pas +++ b/CryptoLib.Tests/src/Crypto/SlhDsaTests.pas @@ -49,6 +49,7 @@ interface FixedSecureRandom, ClpSlhDsaParameters, ClpISlhDsaParameters, + ClpCryptoLibExceptions, ClpSlhDsaGenerators, ClpSlhDsaSigner, ClpHashSlhDsaSigner, @@ -98,12 +99,16 @@ TTestSlhDsa = class(TCryptoLibAlgorithmTestCase) procedure RunParamVectors(const ARelativePath: string; AImpl: TSlhDsaVectorImpl; const AParameters: ISlhDsaParameters; ASampleOnly: Boolean); + procedure ImplComponentEncodingLengths(const AParameters: ISlhDsaParameters); + procedure ExpectBadLengthRejected(const AParameters: ISlhDsaParameters; + const AValid: TCryptoLibByteArray; APrivate: Boolean); public procedure SetUp; override; end; TTestSlhDsaFast = class(TTestSlhDsa) published + procedure TestComponentEncodingLengths; procedure Test02KeyGenAcvp192f; procedure Test04KeyGenAcvpShake256f; procedure Test10ContextFastSha2128f; @@ -302,6 +307,66 @@ procedure TTestSlhDsa.RunSigVer(const ARelativePath: string; RunParamVectors(ARelativePath, ImplSigVer, AParameters, False); end; +procedure TTestSlhDsa.ExpectBadLengthRejected(const AParameters: ISlhDsaParameters; + const AValid: TCryptoLibByteArray; APrivate: Boolean); + + procedure CheckOne(const ABuf: TCryptoLibByteArray); + var + LRaised: Boolean; + begin + LRaised := False; + try + if APrivate then + TSlhDsaPrivateKeyParameters.FromEncoding(AParameters, ABuf) + else + TSlhDsaPublicKeyParameters.FromEncoding(AParameters, ABuf); + except + on E: EArgumentCryptoLibException do + LRaised := True; + end; + CheckTrue(LRaised, 'a wrong-length SLH-DSA component must be rejected'); + end; + +var + LBuf: TCryptoLibByteArray; +begin + LBuf := System.Copy(AValid); + System.SetLength(LBuf, System.Length(AValid) + 1); + CheckOne(LBuf); + + LBuf := System.Copy(AValid); + System.SetLength(LBuf, System.Length(AValid) - 1); + CheckOne(LBuf); +end; + +procedure TTestSlhDsa.ImplComponentEncodingLengths(const AParameters: ISlhDsaParameters); +var + LKpg: IAsymmetricCipherKeyPairGenerator; + LKp: IAsymmetricCipherKeyPair; + LPriv: ISlhDsaPrivateKeyParameters; + LPub: ISlhDsaPublicKeyParameters; + LPrivEnc, LPubEnc: TCryptoLibByteArray; +begin + LKpg := TSlhDsaKeyPairGenerator.Create; + LKpg.Init(TSlhDsaKeyGenerationParameters.Create(FRandom, AParameters) as IKeyGenerationParameters); + LKp := LKpg.GenerateKeyPair; + LPriv := LKp.Private as ISlhDsaPrivateKeyParameters; + LPub := LKp.Public as ISlhDsaPublicKeyParameters; + + LPrivEnc := LPriv.GetEncoded(); + LPubEnc := LPub.GetEncoded(); + + // correctly sized components round-trip + CheckNotNull(TSlhDsaPrivateKeyParameters.FromEncoding(AParameters, LPrivEnc), + 'the private key encoding round-trips'); + CheckNotNull(TSlhDsaPublicKeyParameters.FromEncoding(AParameters, LPubEnc), + 'the public key encoding round-trips'); + + // a component one byte too long or too short is rejected + ExpectBadLengthRejected(AParameters, LPrivEnc, True); + ExpectBadLengthRejected(AParameters, LPubEnc, False); +end; + procedure TTestSlhDsa.ImplConsistency(const AParameters: ISlhDsaParameters); var LMsg: TCryptoLibByteArray; @@ -629,6 +694,11 @@ procedure TTestSlhDsaSlow.Test41ContextSlowShake256sShake256; RunContextVectors('shake-256s-shake256.rsp', TSlhDsaParameters.SlhDsaShake_256sWithShake256, True); end; +procedure TTestSlhDsaFast.TestComponentEncodingLengths; +begin + ImplComponentEncodingLengths(TSlhDsaParameters.SlhDsaSha2_128s); +end; + procedure TTestSlhDsaFast.Test95ConsistencySha2_128s; begin ImplConsistency(TSlhDsaParameters.SlhDsaSha2_128s); diff --git a/CryptoLib.Tests/src/Pkcs/Pkcs12StoreTests.pas b/CryptoLib.Tests/src/Pkcs/Pkcs12StoreTests.pas index 31757492..2e95d81e 100644 --- a/CryptoLib.Tests/src/Pkcs/Pkcs12StoreTests.pas +++ b/CryptoLib.Tests/src/Pkcs/Pkcs12StoreTests.pas @@ -73,6 +73,7 @@ interface CertTestUtilities, CryptoTestKeys, ClpEncoders, + ClpCryptoLibConfig, CryptoLibTestBase, PkcsVectors; @@ -127,6 +128,7 @@ TTestPkcs12Store = class(TCryptoLibAlgorithmTestCase) function GetExpectedPkcs12ChainSerial(AIndex: Int32): TBigInteger; protected procedure SetUp; override; + procedure TearDown; override; published procedure TestCertsOnly; procedure TestPkcs12Store_LoadAndVerifyKeyAndChain; @@ -170,6 +172,7 @@ implementation procedure TTestPkcs12Store.SetUp; begin inherited SetUp; + TCryptoLibConfig.Pkcs12.StoreIterationCount := 1024; FPasswd := StringToCharArray(TPkcs12StoreVectors.GetPassword('MainKeyAndChain')); FNoFriendlyPassword := StringToCharArray(TPkcs12StoreVectors.GetPassword('NoFriendly')); FStoragePassword := StringToCharArray(TPkcs12StoreVectors.GetPassword('StorageIssue')); @@ -196,6 +199,12 @@ procedure TTestPkcs12Store.SetUp; FCertChainCycle := TPkcs12StoreVectors.LoadStoreBytes('CertChainCycle'); end; +procedure TTestPkcs12Store.TearDown; +begin + TCryptoLibConfig.Pkcs12.ResetToDefaults(); + inherited TearDown; +end; + function TTestPkcs12Store.GetFirst(const AAliases: TCryptoLibStringArray): String; begin if (AAliases = nil) or (System.Length(AAliases) = 0) then diff --git a/CryptoLib/src/Asn1/ClpAsn1Dumper.pas b/CryptoLib/src/Asn1/ClpAsn1Dumper.pas index 23bd181e..e2f2bc1e 100644 --- a/CryptoLib/src/Asn1/ClpAsn1Dumper.pas +++ b/CryptoLib/src/Asn1/ClpAsn1Dumper.pas @@ -50,6 +50,12 @@ TAsn1Dumper = class sealed(TObject) const ABytes: TCryptoLibByteArray; AOff, ALen: Int32); static; public + /// Append a formatted dump of a DER object to a caller-supplied buffer (non-verbose). + class procedure AppendAsString(const ABuf: TStringBuilder; + const AObj: IAsn1Encodable); overload; static; + /// Append a formatted dump of a DER object to a caller-supplied buffer. + class procedure AppendAsString(const ABuf: TStringBuilder; const AObj: IAsn1Encodable; + AVerbose: Boolean); overload; static; /// /// Dump out a DER object as a formatted string, in non-verbose mode. /// @@ -366,6 +372,17 @@ class procedure TAsn1Dumper.DumpBinaryDataAsString(const ABuf: TStringBuilder; end; end; +class procedure TAsn1Dumper.AppendAsString(const ABuf: TStringBuilder; const AObj: IAsn1Encodable); +begin + AppendAsString(ABuf, AObj, False); +end; + +class procedure TAsn1Dumper.AppendAsString(const ABuf: TStringBuilder; const AObj: IAsn1Encodable; + AVerbose: Boolean); +begin + AsString('', AVerbose, AObj.ToAsn1Object(), ABuf); +end; + class function TAsn1Dumper.DumpAsString(const AObj: IAsn1Encodable): String; begin Result := DumpAsString(AObj, False); @@ -377,7 +394,7 @@ class function TAsn1Dumper.DumpAsString(const AObj: IAsn1Encodable; AVerbose: Bo begin LBuf := TStringBuilder.Create(); try - AsString('', AVerbose, AObj.ToAsn1Object(), LBuf); + AppendAsString(LBuf, AObj, AVerbose); Result := LBuf.ToString(); finally LBuf.Free; diff --git a/CryptoLib/src/Asn1/ClpAsn1Objects.pas b/CryptoLib/src/Asn1/ClpAsn1Objects.pas index 27639315..e7403ebb 100644 --- a/CryptoLib/src/Asn1/ClpAsn1Objects.pas +++ b/CryptoLib/src/Asn1/ClpAsn1Objects.pas @@ -88,7 +88,6 @@ interface SMalformedBmpStringEncodingEncountered = 'malformed BMPString encoding encountered'; SEofEncounteredReadingBooleanOctet = 'EOF encountered reading BOOLEAN octet'; SBooleanValueShouldHaveOneByte = 'BOOLEAN value should have 1 byte'; - SEnumeratedMustBeNonNegative = 'ENUMERATED must be non-negative'; SMalformedEnumerated = 'malformed ENUMERATED'; SAsn1EnumeratedOutOfIntRange = 'ASN.1 Enumerated out of int range'; SEnumeratedHasZeroLength = 'ENUMERATED has zero length'; @@ -1898,6 +1897,7 @@ Meta = class sealed(TAsn1UniversalType, IAsn1UniversalType) function GetBytes(): TCryptoLibByteArray; function HasValue(AX: Int32): Boolean; overload; function HasValue(const AX: TBigInteger): Boolean; overload; + function TryGetIntValueExact(out AValue: Int32): Boolean; function GetEncoding(AEncoding: Int32): IAsn1Encoding; override; function GetEncodingImplicit(AEncoding, ATagClass, ATagNo: Int32): IAsn1Encoding; override; @@ -8026,9 +8026,6 @@ constructor TDerEnumerated.Create(AVal: Int32); LBytes: TCryptoLibByteArray; begin inherited Create(); - if AVal < 0 then - raise EArgumentCryptoLibException.CreateRes(@SEnumeratedMustBeNonNegative); - LBytes := TBigInteger.ValueOf(AVal).ToByteArray(); FContents := LBytes; FStart := 0; @@ -8039,9 +8036,6 @@ constructor TDerEnumerated.Create(AVal: Int64); LBytes: TCryptoLibByteArray; begin inherited Create(); - if AVal < 0 then - raise EArgumentCryptoLibException.CreateRes(@SEnumeratedMustBeNonNegative); - LBytes := TBigInteger.ValueOf(AVal).ToByteArray(); FContents := LBytes; FStart := 0; @@ -8052,9 +8046,6 @@ constructor TDerEnumerated.Create(const AVal: TBigInteger); LBytes: TCryptoLibByteArray; begin inherited Create(); - if AVal.SignValue < 0 then - raise EArgumentCryptoLibException.CreateRes(@SEnumeratedMustBeNonNegative); - LBytes := AVal.ToByteArray(); FContents := LBytes; FStart := 0; @@ -8070,8 +8061,6 @@ constructor TDerEnumerated.Create(const AContents: TCryptoLibByteArray; AClone: inherited Create(); if TDerInteger.IsMalformed(AContents) then raise EArgumentCryptoLibException.CreateRes(@SMalformedEnumerated); - if (AContents[0] and $80) <> 0 then - raise EArgumentCryptoLibException.CreateRes(@SEnumeratedMustBeNonNegative); if AClone then FContents := System.Copy(AContents) @@ -8116,14 +8105,22 @@ function TDerEnumerated.HasValue(const AX: TBigInteger): Boolean; end; function TDerEnumerated.GetIntValueExact(): Int32; -var - LCount: Int32; begin - LCount := System.Length(FContents) - FStart; - if LCount > 4 then + if not TryGetIntValueExact(Result) then raise EArithmeticCryptoLibException.CreateRes(@SAsn1EnumeratedOutOfIntRange); +end; - Result := TDerInteger.IntValue(FContents, FStart, TDerInteger.SignExtSigned); +function TDerEnumerated.TryGetIntValueExact(out AValue: Int32): Boolean; +begin + if (System.Length(FContents) - FStart) > 4 then + begin + AValue := 0; + Result := False; + Exit; + end; + + AValue := TDerInteger.IntValue(FContents, FStart, TDerInteger.SignExtSigned); + Result := True; end; function TDerEnumerated.GetEncoding(AEncoding: Int32): IAsn1Encoding; diff --git a/CryptoLib/src/Crypto/Signers/SignerCalculators/ClpHMacDsaKCalculator.pas b/CryptoLib/src/Crypto/Signers/SignerCalculators/ClpHMacDsaKCalculator.pas index bc384d9c..00c74146 100644 --- a/CryptoLib/src/Crypto/Signers/SignerCalculators/ClpHMacDsaKCalculator.pas +++ b/CryptoLib/src/Crypto/Signers/SignerCalculators/ClpHMacDsaKCalculator.pas @@ -173,6 +173,10 @@ procedure THMacDsaKCalculator.Init(const AN, AD: TBigInteger; FHmac.BlockUpdate(FV, 0, System.Length(FV)); FHmac.DoFinal(FV, 0); + + // the HMAC seeding is done, so wipe the private scalar's encoding + TArrayUtilities.Fill(LX, 0, System.Length(LX), Byte(0)); + TArrayUtilities.Fill(LDVal, 0, System.Length(LDVal), Byte(0)); end; function THMacDsaKCalculator.NextK: TBigInteger; diff --git a/CryptoLib/src/Interfaces/Asn1/ClpIAsn1Objects.pas b/CryptoLib/src/Interfaces/Asn1/ClpIAsn1Objects.pas index 1fa0541f..e8b61069 100644 --- a/CryptoLib/src/Interfaces/Asn1/ClpIAsn1Objects.pas +++ b/CryptoLib/src/Interfaces/Asn1/ClpIAsn1Objects.pas @@ -713,6 +713,8 @@ interface /// Get the exact Int32 value, throwing if out of range. /// function GetIntValueExact(): Int32; + /// Get the exact Int32 value, returning False instead of throwing if out of range. + function TryGetIntValueExact(out AValue: Int32): Boolean; property Bytes: TCryptoLibByteArray read GetBytes; property Value: TBigInteger read GetValue; property IntValueExact: Int32 read GetIntValueExact; diff --git a/CryptoLib/src/Misc/ClpCryptoLibConfig.pas b/CryptoLib/src/Misc/ClpCryptoLibConfig.pas index b1426bc8..92822e83 100644 --- a/CryptoLib/src/Misc/ClpCryptoLibConfig.pas +++ b/CryptoLib/src/Misc/ClpCryptoLibConfig.pas @@ -460,13 +460,20 @@ TPkcs12Config = class sealed(TObject) const /// Iteration-count ceiling when is unset. DefaultMaxIterationCount = Int32(5000000); + /// Write-side iteration count when is unset or out of range. + DefaultStoreIterationCount = Int32(300000); + /// Upper bound on the write-side count, so the doubled MAC count stays within the default read ceiling. + MaxStoreIterationCount = Int32(2500000); class var FMaxIterationCount: TNullable; + FStoreIterationCount: TNullable; FIgnoreUselessPassword: Boolean; class function GetMaxIterationCount: Int32; static; class procedure SetMaxIterationCount(AValue: Int32); static; + class function GetStoreIterationCount: Int32; static; + class procedure SetStoreIterationCount(AValue: Int32); static; class function GetIgnoreUselessPassword: Boolean; static; class procedure SetIgnoreUselessPassword(AValue: Boolean); static; @@ -481,6 +488,12 @@ TPkcs12Config = class sealed(TObject) /// class property MaxIterationCount: Int32 read GetMaxIterationCount write SetMaxIterationCount; + /// + /// The PBE iteration count used when writing a PKCS#12 keystore; the integrity MAC uses twice + /// this. Defaults to 300,000; a value outside 1 to 2,500,000 is ignored and the default used. + /// + class property StoreIterationCount: Int32 read GetStoreIterationCount write SetStoreIterationCount; + /// /// Loads a PKCS#12 keystore whose integrity is not password-protected without demanding a /// password, rather than rejecting it. Off by default. @@ -905,6 +918,7 @@ class procedure TPbeConfig.SetMaxIterationCount(AValue: Int32); class procedure TPkcs12Config.ResetToDefaults(); begin FMaxIterationCount := TNullable.None; + FStoreIterationCount := TNullable.None; FIgnoreUselessPassword := False; end; @@ -925,6 +939,21 @@ class procedure TPkcs12Config.SetMaxIterationCount(AValue: Int32); FMaxIterationCount := TNullable.Some(AValue); end; +class function TPkcs12Config.GetStoreIterationCount: Int32; +begin + // an out-of-range configured value falls back to the default, so the doubled MAC count is bounded + if FStoreIterationCount.HasValue and (FStoreIterationCount.Value >= 1) and + (FStoreIterationCount.Value <= MaxStoreIterationCount) then + Result := FStoreIterationCount.Value + else + Result := DefaultStoreIterationCount; +end; + +class procedure TPkcs12Config.SetStoreIterationCount(AValue: Int32); +begin + FStoreIterationCount := TNullable.Some(AValue); +end; + class function TPkcs12Config.GetIgnoreUselessPassword: Boolean; begin Result := FIgnoreUselessPassword; diff --git a/CryptoLib/src/Pkcs/ClpPkcs12Store.pas b/CryptoLib/src/Pkcs/ClpPkcs12Store.pas index a431ca15..6af8b92a 100644 --- a/CryptoLib/src/Pkcs/ClpPkcs12Store.pas +++ b/CryptoLib/src/Pkcs/ClpPkcs12Store.pas @@ -188,6 +188,8 @@ TCertID = record const DefaultIterations = 1024; DefaultSaltSize = 20; + /// Floor on a loaded file's MAC salt length when it is carried onto a re-save. + MinMacSaltSize = 8; /// Calculate PBE MAC for PKCS#12 (exposed for Pkcs12Utilities). class function CalculatePbeMac(const AMacAlgID: IAlgorithmIdentifier; const ASalt: TCryptoLibByteArray; AIterations: Int32; @@ -500,9 +502,11 @@ constructor TPkcs12Store.Create(const ACertAlgorithm, ACertPrfAlgorithm, AKeyAlg AUseDerEncoding: Boolean; AReverseCertificates: Boolean; AOverwriteFriendlyName: Boolean; AEnableOracleTrustedKeyUsage: Boolean); begin + // key and certificate encryption use the configured write-side count; the MAC uses twice that Create(ACertAlgorithm, ACertPrfAlgorithm, AKeyAlgorithm, AKeyPrfAlgorithm, AMacDigestAlgorithm, AUseDerEncoding, AReverseCertificates, AOverwriteFriendlyName, AEnableOracleTrustedKeyUsage, - DefaultIterations, DefaultIterations, DefaultIterations, DefaultSaltSize, DefaultSaltSize, DefaultSaltSize); + TCryptoLibConfig.Pkcs12.StoreIterationCount, TCryptoLibConfig.Pkcs12.StoreIterationCount, + 2 * TCryptoLibConfig.Pkcs12.StoreIterationCount, DefaultSaltSize, DefaultSaltSize, DefaultSaltSize); end; constructor TPkcs12Store.Create(const ACertAlgorithm, ACertPrfAlgorithm, AKeyAlgorithm, AKeyPrfAlgorithm, AMacDigestAlgorithm: IDerObjectIdentifier; @@ -844,6 +848,20 @@ procedure TPkcs12Store.Load(const AInput: TStream; const APassword: TCryptoLibCh else raise EIOCryptoLibException.CreateRes(@SMacInvalid); end; + + // the MAC verified, so latch its configuration and reproduce it on a re-save + FMacDigestAlgorithm := LMacData.Mac.DigestAlgorithm.Algorithm; + FMacIterations := TPkcs12Utilities.ValidateIterations(LMacData.Iterations); + FMacSaltSize := System.Length(LMacData.MacSalt.GetOctets()); + if FMacSaltSize < MinMacSaltSize then + FMacSaltSize := MinMacSaltSize; + end + else + begin + // a file without a MAC must not inherit MAC settings carried from an earlier load + FMacDigestAlgorithm := TOiwObjectIdentifiers.IdSha1; + FMacIterations := 2 * TCryptoLibConfig.Pkcs12.StoreIterationCount; + FMacSaltSize := DefaultSaltSize; end; ClearKeys; FLocalIDs.Clear; diff --git a/CryptoLib/src/Pkcs/ClpPkcs12StoreBuilder.pas b/CryptoLib/src/Pkcs/ClpPkcs12StoreBuilder.pas index 54af252a..ac4161a0 100644 --- a/CryptoLib/src/Pkcs/ClpPkcs12StoreBuilder.pas +++ b/CryptoLib/src/Pkcs/ClpPkcs12StoreBuilder.pas @@ -23,6 +23,7 @@ interface uses ClpIAsn1Objects, ClpNistObjectIdentifiers, + ClpCryptoLibConfig, ClpIPkcs12StoreBuilder, ClpIPkcs12Store, ClpPkcs12Store; @@ -169,9 +170,10 @@ constructor TPkcs12StoreBuilder.Create; FReverseCertificates := False; FOverwriteFriendlyName := True; FEnableOracleTrustedKeyUsage := True; - FKeyIterations := TPkcs12Store.DefaultIterations; - FCertIterations := TPkcs12Store.DefaultIterations; - FMacIterations := TPkcs12Store.DefaultIterations; + // key and certificate encryption use the configured write-side count; the MAC uses twice that + FKeyIterations := TCryptoLibConfig.Pkcs12.StoreIterationCount; + FCertIterations := TCryptoLibConfig.Pkcs12.StoreIterationCount; + FMacIterations := 2 * TCryptoLibConfig.Pkcs12.StoreIterationCount; FKeySaltSize := TPkcs12Store.DefaultSaltSize; FCertSaltSize := TPkcs12Store.DefaultSaltSize; FMacSaltSize := TPkcs12Store.DefaultSaltSize; diff --git a/CryptoLib/src/X509/ClpX509Certificate.pas b/CryptoLib/src/X509/ClpX509Certificate.pas index bfa8afe2..6369dbc8 100644 --- a/CryptoLib/src/X509/ClpX509Certificate.pas +++ b/CryptoLib/src/X509/ClpX509Certificate.pas @@ -863,7 +863,8 @@ function TX509Certificate.ToString: String; else begin LBuf.Append(LOid.Id); - LBuf.Append(' value = ').Append(TAsn1Dumper.DumpAsString(LObj)); + LBuf.Append(' value = '); + TAsn1Dumper.AppendAsString(LBuf, LObj); end; except on E: Exception do