Ugochukwu Mmaduekwe hace 1 semana
padre
commit
00e5e9cf64
Se han modificado 23 ficheros con 1422 adiciones y 1615 borrados
  1. 11 13
      CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.dpr
  2. 128 0
      CryptoLib.Tests/src/Asn1/Pkcs/Pkcs10CertRequestTests.pas
  3. 30 30
      CryptoLib.Tests/src/Math/ECIESTests.pas
  4. 41 45
      CryptoLib.Tests/src/Math/IESCipherTests.pas
  5. 106 90
      CryptoLib.Tests/src/Math/PascalCoinECIESTests.pas
  6. 194 0
      CryptoLib/src/Crypto/Ciphers/ClpBufferedIesCipher.pas
  7. 21 1
      CryptoLib/src/Crypto/Ciphers/ClpCipherUtilities.pas
  8. 0 300
      CryptoLib/src/Crypto/Ciphers/ClpIESCipher.pas
  9. 0 636
      CryptoLib/src/Crypto/Engines/ClpIESEngine.pas
  10. 645 0
      CryptoLib/src/Crypto/Engines/ClpIesEngine.pas
  11. 85 85
      CryptoLib/src/Crypto/Engines/ClpPascalCoinIesEngine.pas
  12. 81 0
      CryptoLib/src/Crypto/Parameters/ClpIesCipherParameters.pas
  13. 17 17
      CryptoLib/src/Crypto/Parameters/ClpIesParameters.pas
  14. 14 14
      CryptoLib/src/Crypto/Parameters/ClpIesWithCipherParameters.pas
  15. 0 205
      CryptoLib/src/Interfaces/ClpIESParameterSpec.pas
  16. 0 90
      CryptoLib/src/Interfaces/ClpIIESParameterSpec.pas
  17. 0 54
      CryptoLib/src/Interfaces/Crypto/Ciphers/ClpIIESCipher.pas
  18. 23 23
      CryptoLib/src/Interfaces/Crypto/Engines/ClpIIesEngine.pas
  19. 2 2
      CryptoLib/src/Interfaces/Crypto/Engines/ClpIPascalCoinIesEngine.pas
  20. 20 4
      CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIesCipherParameters.pas
  21. 2 2
      CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIesParameters.pas
  22. 2 2
      CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIesWithCipherParameters.pas
  23. 0 2
      CryptoLib/src/Math/ClpBigInteger.pas

+ 11 - 13
CryptoLib.Tests/Delphi.Tests/CryptoLib.Tests.dpr

@@ -53,6 +53,7 @@ uses
   ClpBufferedBlockCipher in '..\..\CryptoLib\src\Crypto\Ciphers\ClpBufferedBlockCipher.pas',
   ClpBufferedCipherBase in '..\..\CryptoLib\src\Crypto\Ciphers\ClpBufferedCipherBase.pas',
   ClpBufferedStreamCipher in '..\..\CryptoLib\src\Crypto\Ciphers\ClpBufferedStreamCipher.pas',
+  ClpBufferedIesCipher in '..\..\CryptoLib\src\Crypto\Ciphers\ClpBufferedIesCipher.pas',
   ClpChaChaEngine in '..\..\CryptoLib\src\Crypto\Engines\ClpChaChaEngine.pas',
   ClpCheck in '..\..\CryptoLib\src\Crypto\ClpCheck.pas',
   ClpCodec in '..\..\CryptoLib\src\Math\EC\Rfc8032\ClpCodec.pas',
@@ -151,7 +152,6 @@ uses
   ClpHMacDsaKCalculator in '..\..\CryptoLib\src\Crypto\Signers\SignerCalculators\ClpHMacDsaKCalculator.pas',
   ClpIAesEngine in '..\..\CryptoLib\src\Interfaces\Crypto\Engines\ClpIAesEngine.pas',
   ClpIAesLightEngine in '..\..\CryptoLib\src\Interfaces\Crypto\Engines\ClpIAesLightEngine.pas',
-  ClpIAlgorithmParameterSpec in '..\..\CryptoLib\src\Interfaces\ClpIAlgorithmParameterSpec.pas',
   ClpIanaObjectIdentifiers in '..\..\CryptoLib\src\Asn1\Iana\ClpIanaObjectIdentifiers.pas',
   ClpIArgon2ParametersGenerator in '..\..\CryptoLib\src\Interfaces\Crypto\Generators\ClpIArgon2ParametersGenerator.pas',
   ClpIAsn1Objects in '..\..\CryptoLib\src\Interfaces\Asn1\ClpIAsn1Objects.pas',
@@ -228,11 +228,10 @@ uses
   ClpIEndoPreCompInfo in '..\..\CryptoLib\src\Interfaces\Math\EC\Endo\ClpIEndoPreCompInfo.pas',
   ClpIEphemeralKeyPair in '..\..\CryptoLib\src\Interfaces\Crypto\ClpIEphemeralKeyPair.pas',
   ClpIEphemeralKeyPairGenerator in '..\..\CryptoLib\src\Interfaces\Crypto\Generators\ClpIEphemeralKeyPairGenerator.pas',
-  ClpIESCipher in '..\..\CryptoLib\src\Crypto\Ciphers\ClpIESCipher.pas',
-  ClpIESEngine in '..\..\CryptoLib\src\Crypto\Engines\ClpIESEngine.pas',
-  ClpIESParameters in '..\..\CryptoLib\src\Crypto\Parameters\ClpIESParameters.pas',
-  ClpIESParameterSpec in '..\..\CryptoLib\src\Interfaces\ClpIESParameterSpec.pas',
-  ClpIESWithCipherParameters in '..\..\CryptoLib\src\Crypto\Parameters\ClpIESWithCipherParameters.pas',
+  ClpIesEngine in '..\..\CryptoLib\src\Crypto\Engines\ClpIesEngine.pas',
+  ClpIesParameters in '..\..\CryptoLib\src\Crypto\Parameters\ClpIesParameters.pas',
+  ClpIesCipherParameters in '..\..\CryptoLib\src\Crypto\Parameters\ClpIesCipherParameters.pas',
+  ClpIesWithCipherParameters in '..\..\CryptoLib\src\Crypto\Parameters\ClpIesWithCipherParameters.pas',
   ClpIetfUtilities in '..\..\CryptoLib\src\Asn1\X500\Style\ClpIetfUtilities.pas',
   ClpIExtensionField in '..\..\CryptoLib\src\Interfaces\Math\Field\ClpIExtensionField.pas',
   ClpIFiniteField in '..\..\CryptoLib\src\Interfaces\Math\Field\ClpIFiniteField.pas',
@@ -249,11 +248,10 @@ uses
   ClpIHkdfParameters in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIHkdfParameters.pas',
   ClpIHMac in '..\..\CryptoLib\src\Interfaces\Crypto\Macs\ClpIHMac.pas',
   ClpIHMacDsaKCalculator in '..\..\CryptoLib\src\Interfaces\Crypto\Signers\SignerCalculators\ClpIHMacDsaKCalculator.pas',
-  ClpIIESCipher in '..\..\CryptoLib\src\Interfaces\Crypto\Ciphers\ClpIIESCipher.pas',
-  ClpIIESEngine in '..\..\CryptoLib\src\Interfaces\Crypto\Engines\ClpIIESEngine.pas',
-  ClpIIESParameters in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIIESParameters.pas',
-  ClpIIESParameterSpec in '..\..\CryptoLib\src\Interfaces\ClpIIESParameterSpec.pas',
-  ClpIIESWithCipherParameters in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIIESWithCipherParameters.pas',
+  ClpIIesEngine in '..\..\CryptoLib\src\Interfaces\Crypto\Engines\ClpIIesEngine.pas',
+  ClpIIesParameters in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIIesParameters.pas',
+  ClpIIesCipherParameters in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIIesCipherParameters.pas',
+  ClpIIesWithCipherParameters in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIIesWithCipherParameters.pas',
   ClpIIso18033KdfParameters in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIIso18033KdfParameters.pas',
   ClpIISO9796d1Encoding in '..\..\CryptoLib\src\Interfaces\Crypto\Encodings\ClpIISO9796d1Encoding.pas',
   ClpIKdf1BytesGenerator in '..\..\CryptoLib\src\Interfaces\Crypto\Generators\ClpIKdf1BytesGenerator.pas',
@@ -275,7 +273,7 @@ uses
   ClpIParametersWithIV in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIParametersWithIV.pas',
   ClpIParametersWithRandom in '..\..\CryptoLib\src\Interfaces\Crypto\Parameters\ClpIParametersWithRandom.pas',
   ClpIPascalCoinECIESKdfBytesGenerator in '..\..\CryptoLib\src\Interfaces\Crypto\Generators\ClpIPascalCoinECIESKdfBytesGenerator.pas',
-  ClpIPascalCoinIESEngine in '..\..\CryptoLib\src\Interfaces\Crypto\Engines\ClpIPascalCoinIESEngine.pas',
+  ClpIPascalCoinIesEngine in '..\..\CryptoLib\src\Interfaces\Crypto\Engines\ClpIPascalCoinIesEngine.pas',
   ClpIPbeParametersGenerator in '..\..\CryptoLib\src\Interfaces\Crypto\Generators\ClpIPbeParametersGenerator.pas',
   ClpIPemObjects in '..\..\CryptoLib\src\Interfaces\Pem\ClpIPemObjects.pas',
   ClpIPkcs1Encoding in '..\..\CryptoLib\src\Interfaces\Crypto\Encodings\ClpIPkcs1Encoding.pas',
@@ -371,7 +369,7 @@ uses
   ClpParametersWithRandom in '..\..\CryptoLib\src\Crypto\Parameters\ClpParametersWithRandom.pas',
   ClpParameterUtilities in '..\..\CryptoLib\src\Crypto\Parameters\ClpParameterUtilities.pas',
   ClpPascalCoinECIESKdfBytesGenerator in '..\..\CryptoLib\src\Crypto\Generators\ClpPascalCoinECIESKdfBytesGenerator.pas',
-  ClpPascalCoinIESEngine in '..\..\CryptoLib\src\Crypto\Engines\ClpPascalCoinIESEngine.pas',
+  ClpPascalCoinIesEngine in '..\..\CryptoLib\src\Crypto\Engines\ClpPascalCoinIesEngine.pas',
   ClpPbeParametersGenerator in '..\..\CryptoLib\src\Crypto\Generators\ClpPbeParametersGenerator.pas',
   ClpPemObjects in '..\..\CryptoLib\src\Pem\ClpPemObjects.pas',
   ClpPkcs1Encoding in '..\..\CryptoLib\src\Crypto\Encodings\ClpPkcs1Encoding.pas',

+ 128 - 0
CryptoLib.Tests/src/Asn1/Pkcs/Pkcs10CertRequestTests.pas

@@ -0,0 +1,128 @@
+{ *********************************************************************************** }
+{ *                              CryptoLib Library                                  * }
+{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
+{ *                 Github Repository <https://github.com/Xor-el>                   * }
+
+{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
+{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
+
+{ *                              Acknowledgements:                                  * }
+{ *                                                                                 * }
+{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
+{ *                           development of this library                           * }
+
+{ * ******************************************************************************* * }
+
+(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
+
+unit Pkcs10CertRequestTests;
+
+interface
+
+{$IFDEF FPC}
+{$MODE DELPHI}
+{$ENDIF FPC}
+
+uses
+  SysUtils,
+{$IFDEF FPC}
+  fpcunit,
+  testregistry,
+{$ELSE}
+  TestFramework,
+{$ENDIF FPC}
+  ClpPkcsAsn1Objects,
+  ClpIPkcsAsn1Objects,
+  ClpCryptoLibTypes,
+  CryptoLibTestBase;
+
+type
+
+  TPkcs10CertRequestTest = class(TCryptoLibAlgorithmTestCase)
+  strict private
+    var
+      FReq1: TCryptoLibByteArray;
+      FReq2: TCryptoLibByteArray;
+
+    procedure SetUpTestData;
+    procedure BasicPkcs10Test(const ATestName: String; const AReq: TCryptoLibByteArray);
+
+  protected
+    procedure SetUp; override;
+
+  published
+    procedure TestBasicCR;
+    procedure TestUniversalCR;
+
+  end;
+
+implementation
+
+{ TPkcs10CertRequestTest }
+
+procedure TPkcs10CertRequestTest.SetUpTestData;
+begin
+  FReq1 := DecodeBase64('MIHoMIGTAgEAMC4xDjAMBgNVBAMTBVRlc3QyMQ8wDQYDVQQKEwZBbmFUb20xCzAJBgNVBAYTAlNF' +
+    'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALlEt31Tzt2MlcOljvacJgzQVhmlMoqAOgqJ9Pgd3Gux' +
+    'Z7/WcIlgW4QCB7WZT21O1YoghwBhPDMcNGrHei9kHQkCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA0EA' +
+    'NDEI4ecNtJ3uHwGGlitNFq9WxcoZ0djbQJ5hABMotav6gtqlrwKXY2evaIrsNwkJtNdwwH18aQDU' +
+    'KCjOuBL38Q==');
+
+  FReq2 := DecodeBase64('MIIB6TCCAVICAQAwgagxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQH' +
+    'EwtTYW50YSBDbGFyYTEMMAoGA1UEChMDQUJCMVEwTwYDVQQLHEhQAAAAAAAAAG8AAAAAAAAAdwAA' +
+    'AAAAAABlAAAAAAAAAHIAAAAAAAAAIAAAAAAAAABUAAAAAAAAABxIAAAAAAAARAAAAAAAAAAxDTAL' +
+    'BgNVBAMTBGJsdWUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANETRZ+6occCOrFxNhfKIp4C' +
+    'mMkxwhBNb7TnnahpbM9O0r4hrBPcfYuL7u9YX/jN0YNUP+/CiT39HhSe/bikaBPDEyNsl988I8vX' +
+    'piEdgxYq/+LTgGHbjRsRYCkPtmzwBbuBldNF8bV7pu0v4UScSsExmGqqDlX1TbPU8KkPU1iTAgMB' +
+    'AAGgADANBgkqhkiG9w0BAQQFAAOBgQAFbrs9qUwh93CtETk7DeUD5HcdCnxauo1bck44snSV6MZV' +
+    'OCIGaYu1501kmhEvAtVVRr6SEHwimfQDDIjnrWwYsEr/DT6tkTZAbfRd3qUu3iKjT0H0vlUZp0hJ' +
+    '66mINtBM84uZFBfoXiWY8M3FuAnGmvy6ah/dYtJorTxLKiGkew==');
+end;
+
+procedure TPkcs10CertRequestTest.SetUp;
+begin
+  inherited SetUp;
+  SetUpTestData;
+end;
+
+procedure TPkcs10CertRequestTest.BasicPkcs10Test(const ATestName: String; const AReq: TCryptoLibByteArray);
+var
+  LCertReq: ICertificationRequest;
+  LBytes: TCryptoLibByteArray;
+begin
+  try
+    LCertReq := TCertificationRequest.GetInstance(AReq);
+
+    LBytes := LCertReq.GetDerEncoded();
+
+    if not AreEqual(LBytes, AReq) then
+    begin
+      Fail(Format('Pkcs10: %s failed comparison test', [ATestName]));
+    end;
+  except
+    on E: Exception do
+    begin
+      Fail(Format('Pkcs10: Exception - %s %s', [ATestName, E.Message]));
+    end;
+  end;
+end;
+
+procedure TPkcs10CertRequestTest.TestBasicCR;
+begin
+  BasicPkcs10Test('Basic CR', FReq1);
+end;
+
+procedure TPkcs10CertRequestTest.TestUniversalCR;
+begin
+  BasicPkcs10Test('Universal CR', FReq2);
+end;
+
+initialization
+
+{$IFDEF FPC}
+RegisterTest(TPkcs10CertRequestTest);
+{$ELSE}
+RegisterTest(TPkcs10CertRequestTest.Suite);
+{$ENDIF FPC}
+
+end.

+ 30 - 30
CryptoLib.Tests/src/Math/ECIESTests.pas

@@ -115,7 +115,7 @@ var
   pubKey: IECPublicKeyParameters;
   p1: IAsymmetricCipherKeyPair;
   p: ICipherParameters;
-  i1, i2: IIESEngine;
+  i1, i2: IIesEngine;
   d, e, &message, out1, out2: TBytes;
   gen: IECKeyPairGenerator;
   ephKeyGen: IEphemeralKeyPairGenerator;
@@ -163,19 +163,19 @@ begin
   //
   // stream test
   //
-  i1 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i1 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
-  i2 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i2 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
   d := TBytes.Create(1, 2, 3, 4, 5, 6, 7, 8);
   e := TBytes.Create(8, 7, 6, 5, 4, 3, 2, 1);
-  p := TIESParameters.Create(d, e, 64);
+  p := TIesParameters.Create(d, e, 64);
 
   i1.Init(p1.Public, p, ephKeyGen);
   i2.Init(p1.Private, p, TECIESPublicKeyParser.Create(params)
@@ -203,19 +203,19 @@ begin
     (TCBCBlockCipher.Create(TAesEngine.Create() as IAesEngine)
     as ICBCBlockCipher);
 
-  i1 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i1 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac, c1);
 
-  i2 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i2 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac, c2);
 
   d := TBytes.Create(1, 2, 3, 4, 5, 6, 7, 8);
   e := TBytes.Create(8, 7, 6, 5, 4, 3, 2, 1);
-  p := TIESWithCipherParameters.Create(d, e, 64, 128);
+  p := TIesWithCipherParameters.Create(d, e, 64, 128);
 
   if (iv <> Nil) then
   begin
@@ -247,7 +247,7 @@ var
   pubKey: IECPublicKeyParameters;
   p1, p2: IAsymmetricCipherKeyPair;
   p: ICipherParameters;
-  i1, i2: IIESEngine;
+  i1, i2: IIesEngine;
   d, e, &message, out1, out2: TBytes;
   gen: IECKeyPairGenerator;
   ephKeyGen: IEphemeralKeyPairGenerator;
@@ -285,22 +285,22 @@ begin
   //
   // stream test - V 0
   //
-  i1 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i1 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
-  i2 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i2 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
   d := TBytes.Create(1, 2, 3, 4, 5, 6, 7, 8);
   e := TBytes.Create(8, 7, 6, 5, 4, 3, 2, 1);
-  p := TIESParameters.Create(d, e, 64);
+  p := TIesParameters.Create(d, e, 64);
 
   i1.Init(true, p1.Private, p2.Public, p);
-  i2.Init(false, p2.getPrivate, p1.getPublic, p);
+  i2.Init(false, p2.Private, p1.Public, p);
 
   &message := Nil;
 
@@ -385,7 +385,7 @@ var
   pubKey: IECPublicKeyParameters;
   p1, p2: IAsymmetricCipherKeyPair;
   p: ICipherParameters;
-  i1, i2: IIESEngine;
+  i1, i2: IIesEngine;
   d, e, &message, out1, out2, compareValue: TBytes;
   c1, c2: IBufferedBlockCipher;
 begin
@@ -422,22 +422,22 @@ begin
   //
   // stream test
   //
-  i1 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i1 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
-  i2 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i2 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
   d := TBytes.Create(1, 2, 3, 4, 5, 6, 7, 8);
   e := TBytes.Create(8, 7, 6, 5, 4, 3, 2, 1);
-  p := TIESParameters.Create(d, e, 64);
+  p := TIesParameters.Create(d, e, 64);
 
   i1.Init(true, p1.Private, p2.Public, p);
-  i2.Init(false, p2.getPrivate, p1.getPublic, p);
+  i2.Init(false, p2.Private, p1.Public, p);
 
   &message := DecodeHex('1234567890abcdef');
 
@@ -468,19 +468,19 @@ begin
     (TCBCBlockCipher.Create(TAesEngine.Create() as IAesEngine)
     as ICBCBlockCipher);
 
-  i1 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i1 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac, c1);
 
-  i2 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i2 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac, c2);
 
   d := TBytes.Create(1, 2, 3, 4, 5, 6, 7, 8);
   e := TBytes.Create(8, 7, 6, 5, 4, 3, 2, 1);
-  p := TIESWithCipherParameters.Create(d, e, 64, 128);
+  p := TIesWithCipherParameters.Create(d, e, 64, 128);
 
   if (iv <> Nil) then
   begin
@@ -524,29 +524,29 @@ end;
 procedure TTestECIES.DoTest(const p1, p2: IAsymmetricCipherKeyPair);
 var
   p: ICipherParameters;
-  i1, i2: IIESEngine;
+  i1, i2: IIesEngine;
   d, e, &message, out1, out2: TBytes;
   c1, c2: IBufferedBlockCipher;
 begin
   //
   // stream test
   //
-  i1 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i1 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
-  i2 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i2 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac);
 
   d := TBytes.Create(1, 2, 3, 4, 5, 6, 7, 8);
   e := TBytes.Create(8, 7, 6, 5, 4, 3, 2, 1);
-  p := TIESParameters.Create(d, e, 64);
+  p := TIesParameters.Create(d, e, 64);
 
   i1.Init(true, p1.Private, p2.Public, p);
-  i2.Init(false, p2.getPrivate, p1.getPublic, p);
+  i2.Init(false, p2.Private, p1.Public, p);
 
   &message := DecodeHex('1234567890abcdef');
 
@@ -571,19 +571,19 @@ begin
     (TCBCBlockCipher.Create(TAesEngine.Create() as IAesEngine)
     as ICBCBlockCipher);
 
-  i1 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i1 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac, c1);
 
-  i2 := TIESEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+  i2 := TIesEngine.Create(TECDHBasicAgreement.Create() as IECDHBasicAgreement,
     TKDF2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IKDF2BytesGenerator, THMac.Create(TDigestUtilities.GetDigest('SHA-1'))
     as IHMac, c2);
 
   d := TBytes.Create(1, 2, 3, 4, 5, 6, 7, 8);
   e := TBytes.Create(8, 7, 6, 5, 4, 3, 2, 1);
-  p := TIESWithCipherParameters.Create(d, e, 64, 128);
+  p := TIesWithCipherParameters.Create(d, e, 64, 128);
 
   i1.Init(true, p1.Private, p2.Public, p);
   i2.Init(false, p2.Private, p1.Public, p);
@@ -648,8 +648,8 @@ begin
 
   eGen.Init(gParam);
 
-  p1 := eGen.generateKeyPair();
-  p2 := eGen.generateKeyPair();
+  p1 := eGen.GenerateKeyPair();
+  p2 := eGen.GenerateKeyPair();
 
   DoTest(p1, p2);
 

+ 41 - 45
CryptoLib.Tests/src/Math/IESCipherTests.pas

@@ -36,8 +36,13 @@ uses
   ClpIAesEngine,
   ClpIAsymmetricCipherKeyPairGenerator,
   ClpGeneratorUtilities,
-  ClpIESParameterSpec,
-  ClpIAlgorithmParameterSpec,
+  ClpICipherParameters,
+  ClpIIESParameters,
+  ClpIIESWithCipherParameters,
+  ClpIESParameters,
+  ClpIESWithCipherParameters,
+  ClpParametersWithIV,
+  ClpIParametersWithIV,
   // ClpKeyParameter,
   // ClpIKeyParameter,
   // ClpParametersWithIV,
@@ -66,8 +71,10 @@ uses
   ClpIAsymmetricCipherKeyPair,
   ClpIECPublicKeyParameters,
   ClpIECPrivateKeyParameters,
-  ClpIIESCipher,
-  ClpIESCipher,
+  ClpIIesCipherParameters,
+  ClpIesCipherParameters,
+  ClpIBufferedCipher,
+  ClpBufferedIesCipher,
   ClpDigestUtilities,
   ClpMacUtilities,
   ClpConverters,
@@ -78,13 +85,13 @@ type
   TTestIESCipher = class(TCryptoLibAlgorithmTestCase)
   private
 
-    function GetECIESAES256CBCEngine: IIESEngine;
+    function GetECIESAES256CBCEngine: IIesEngine;
     function GetECKeyPair: IAsymmetricCipherKeyPair;
-    function GetIESParameterSpec: IAlgorithmParameterSpec;
+    function GetIESParameters: ICipherParameters;
 
     procedure DoIESCipher_Encryption_Decryption_TestWithIV
       (const KeyPair: IAsymmetricCipherKeyPair;
-      const param: IAlgorithmParameterSpec; const Random: ISecureRandom;
+      const AParams: ICipherParameters; const Random: ISecureRandom;
       const PlainText: String);
 
   protected
@@ -102,23 +109,27 @@ implementation
 
 procedure TTestIESCipher.DoIESCipher_Encryption_Decryption_TestWithIV
   (const KeyPair: IAsymmetricCipherKeyPair;
-  const param: IAlgorithmParameterSpec; const Random: ISecureRandom;
+  const AParams: ICipherParameters; const Random: ISecureRandom;
   const PlainText: String);
 var
   PlainTextBytes, CipherTextBytes, DecryptionResultBytes: TBytes;
-  CipherEncrypt, CipherDecrypt: IIESCipher;
+  CipherEncrypt, CipherDecrypt: IBufferedCipher;
+  LParamsWithIV: IParametersWithIV;
+  LIesParams: IIesParameters;
+  LCipherParams: IIesCipherParameters;
 begin
   PlainTextBytes := TConverters.ConvertStringToBytes(PlainText, TEncoding.UTF8);
-  // Encryption
-  CipherEncrypt := TIESCipher.Create(GetECIESAES256CBCEngine);
-  CipherEncrypt.Init(True, KeyPair.Public as IECPublicKeyParameters,
-    param, Random);
+  if not Supports(AParams, IParametersWithIV, LParamsWithIV) or
+     not Supports(LParamsWithIV.Parameters, IIesParameters, LIesParams) then
+    Fail('GetIESParameters must return IParametersWithIV wrapping IIESParameters');
+  LCipherParams := TIesCipherParameters.Create(KeyPair.Private, KeyPair.Public, LIesParams);
+
+  CipherEncrypt := TBufferedIesCipher.Create(GetECIESAES256CBCEngine);
+  CipherEncrypt.Init(True, LCipherParams);
   CipherTextBytes := CipherEncrypt.DoFinal(PlainTextBytes);
 
-  // Decryption
-  CipherDecrypt := TIESCipher.Create(GetECIESAES256CBCEngine);
-  CipherDecrypt.Init(False, KeyPair.Private as IECPrivateKeyParameters,
-    param, Random);
+  CipherDecrypt := TBufferedIesCipher.Create(GetECIESAES256CBCEngine);
+  CipherDecrypt.Init(False, LCipherParams);
   DecryptionResultBytes := CipherDecrypt.DoFinal(CipherTextBytes);
 
   if (not AreEqual(PlainTextBytes, DecryptionResultBytes)) then
@@ -128,7 +139,7 @@ begin
   end;
 end;
 
-function TTestIESCipher.GetECIESAES256CBCEngine: IIESEngine;
+function TTestIESCipher.GetECIESAES256CBCEngine: IIesEngine;
 var
   Cipher: IBufferedBlockCipher;
   AesEngine: IAesEngine;
@@ -161,7 +172,7 @@ begin
   // Cipher := TPaddedBufferedBlockCipher.Create(blockCipher,
   // TZeroBytePadding.Create() as IZeroBytePadding); // ZeroBytePadding
 
-  result := TIESEngine.Create(ECDHBasicAgreementInstance, KDFInstance,
+  result := TIesEngine.Create(ECDHBasicAgreementInstance, KDFInstance,
     DigestMACInstance, Cipher);
 end;
 
@@ -186,35 +197,20 @@ begin
   result := KeyPairGeneratorInstance.GenerateKeyPair();
 end;
 
-function TTestIESCipher.GetIESParameterSpec: IAlgorithmParameterSpec;
+function TTestIESCipher.GetIESParameters: ICipherParameters;
 var
   Derivation, Encoding, IVBytes: TBytes;
   MacKeySizeInBits, CipherKeySizeInBits: Int32;
-  UsePointCompression: Boolean;
+  LIesParams: IIesWithCipherParameters;
 begin
-  // Setup IES With Cipher Parameters
-
-  // The derivation and encoding vectors are used when initialising the KDF and MAC.
-  // They're optional but if used then they need to be known by the other user so that
-  // they can decrypt the ciphertext and verify the MAC correctly. The security is based
-  // on the shared secret coming from the (static-ephemeral) ECDH key agreement.
-  Derivation := Nil;
-
-  Encoding := Nil;
-
-  System.SetLength(IVBytes, 16); // using Zero Initialized IV for ease
-
-  MacKeySizeInBits := 32 * 8; // Since we are using SHA2_256 for MAC
-
-  CipherKeySizeInBits := 32 * 8; // Since we are using AES256 for Cipher
-
-  // whether to use point compression when deriving the octets string
-  // from a point or not in the EphemeralKeyPairGenerator
-  UsePointCompression := False;
-
-  result := TIESParameterSpec.Create(Derivation, Encoding, MacKeySizeInBits,
-    CipherKeySizeInBits, IVBytes, UsePointCompression);
-
+  Derivation := nil;
+  Encoding := nil;
+  System.SetLength(IVBytes, 16); // Zero-initialized IV
+  MacKeySizeInBits := 32 * 8;   // SHA2_256 for MAC
+  CipherKeySizeInBits := 32 * 8; // AES256
+  LIesParams := TIesWithCipherParameters.Create(Derivation, Encoding,
+    MacKeySizeInBits, CipherKeySizeInBits);
+  Result := TParametersWithIV.Create(LIesParams, IVBytes);
 end;
 
 procedure TTestIESCipher.SetUp;
@@ -247,7 +243,7 @@ begin
     // Call IESCipher Encryption and Decryption Method
 
     DoIESCipher_Encryption_Decryption_TestWithIV(GetECKeyPair,
-      GetIESParameterSpec, RandomInstance, PlainText);
+      GetIESParameters, RandomInstance, PlainText);
 
     System.Inc(I);
   end;

+ 106 - 90
CryptoLib.Tests/src/Math/PascalCoinECIESTests.pas

@@ -17,8 +17,18 @@ uses
 {$ENDIF FPC}
   ClpIECC,
   ClpIESEngine,
-  ClpIIESCipher,
-  ClpIESCipher,
+  ClpIIESEngine,
+  ClpIKeyParser,
+  ClpIECIESPublicKeyParser,
+  ClpECIESPublicKeyParser,
+  ClpIEphemeralKeyPairGenerator,
+  ClpEphemeralKeyPairGenerator,
+  ClpIECKeyPairGenerator,
+  ClpECKeyPairGenerator,
+  ClpECKeyGenerationParameters,
+  ClpIECKeyGenerationParameters,
+  ClpIKeyEncoder,
+  ClpKeyEncoder,
   ClpIECDHBasicAgreement,
   ClpECDHBasicAgreement,
   ClpECPrivateKeyParameters,
@@ -38,8 +48,13 @@ uses
   ClpBigInteger,
   ClpCustomNamedCurves,
   ClpDigestUtilities,
-  ClpIIESParameterSpec,
-  ClpIESParameterSpec,
+  ClpICipherParameters,
+  ClpIIESParameters,
+  ClpIIESWithCipherParameters,
+  ClpIESParameters,
+  ClpIESWithCipherParameters,
+  ClpParametersWithIV,
+  ClpIParametersWithIV,
   ClpIPascalCoinIESEngine,
   ClpPascalCoinIESEngine,
   ClpPascalCoinECIESKdfBytesGenerator,
@@ -75,27 +90,27 @@ type
   var
     FRandom: ISecureRandom;
 
-    function GetCurveFromKeyType(keyType: TKeyType): IX9ECParameters;
-    function GetPascalCoinIESParameterSpec: IIESParameterSpec;
-    function GetECIESPascalCoinCompatibilityEngine: IPascalCoinIESEngine;
+    function GetCurveFromKeyType(AKeyType: TKeyType): IX9ECParameters;
+    function GetPascalCoinIESParameters: ICipherParameters;
+    function GetECIESPascalCoinCompatibilityEngine: IPascalCoinIesEngine;
 
-    function RecreatePublicKeyFromAffineXandAffineYCoord(keyType: TKeyType;
+    function RecreatePublicKeyFromAffineXandAffineYCoord(AKeyType: TKeyType;
       const RawAffineX, RawAffineY: TBytes): IECPublicKeyParameters;
 
-    function RecreatePrivateKeyFromByteArray(keyType: TKeyType;
+    function RecreatePrivateKeyFromByteArray(AKeyType: TKeyType;
       const RawPrivateKey: TBytes): IECPrivateKeyParameters;
 
-    function DoPascalCoinECIESEncrypt(keyType: TKeyType;
+    function DoPascalCoinECIESEncrypt(AKeyType: TKeyType;
       const RawAffineXCoord, RawAffineYCoord, PayloadToEncrypt: String): String;
 
-    function DoPascalCoinECIESDecrypt(keyType: TKeyType;
+    function DoPascalCoinECIESDecrypt(AKeyType: TKeyType;
       const RawPrivateKey, PayloadToDecrypt: String): String;
 
-    procedure DoTestPascalCoinECIESDecrypt(const id: String; keyType: TKeyType;
+    procedure DoTestPascalCoinECIESDecrypt(const AId: String; AKeyType: TKeyType;
       const RawPrivateKey, PayloadToDecrypt, ExpectedOutput: String);
 
-    procedure DoTestPascalCoinECIESEncryptDecrypt(const id: String;
-      keyType: TKeyType; const RawPrivateKey, RawAffineXCoord, RawAffineYCoord,
+    procedure DoTestPascalCoinECIESEncryptDecrypt(const AId: String;
+      AKeyType: TKeyType; const RawPrivateKey, RawAffineXCoord, RawAffineYCoord,
       PayloadToEncrypt: String);
 
   protected
@@ -124,80 +139,65 @@ begin
   FRandom := Nil;
 end;
 
-function TTestPascalCoinECIES.GetCurveFromKeyType(keyType: TKeyType)
+function TTestPascalCoinECIES.GetCurveFromKeyType(AKeyType: TKeyType)
   : IX9ECParameters;
 var
-  CurveName: string;
+  LCurveName: String;
 begin
-  CurveName := GetEnumName(TypeInfo(TKeyType), Ord(keyType));
-  Result := TCustomNamedCurves.GetByName(CurveName);
+  LCurveName := GetEnumName(TypeInfo(TKeyType), Ord(AKeyType));
+  Result := TCustomNamedCurves.GetByName(LCurveName);
 end;
 
-function TTestPascalCoinECIES.GetPascalCoinIESParameterSpec: IIESParameterSpec;
+function TTestPascalCoinECIES.GetPascalCoinIESParameters: ICipherParameters;
 var
-  Derivation, Encoding, IVBytes: TBytes;
-  MacKeySizeInBits, CipherKeySizeInBits: Int32;
-  UsePointCompression: boolean;
+  LDerivation, LEncoding, LIVBytes: TBytes;
+  LMacKeySizeInBits, LCipherKeySizeInBits: Int32;
+  LIesParams: IIesWithCipherParameters;
 begin
-  // Set up IES Parameter Spec For Compatibility With PascalCoin Current Implementation
-
-  // The derivation and encoding vectors are used when initialising the KDF and MAC.
-  // They're optional but if used then they need to be known by the other user so that
-  // they can decrypt the ciphertext and verify the MAC correctly. The security is based
-  // on the shared secret coming from the (static-ephemeral) ECDH key agreement.
-  Derivation := nil;
-
-  Encoding := nil;
-
-  System.SetLength(IVBytes, 16); // using Zero Initialized IV for compatibility
-
-  MacKeySizeInBits := 32 * 8;
-
-  // Since we are using AES256_CBC for compatibility
-  CipherKeySizeInBits := 32 * 8;
-
-  // whether to use point compression when deriving the octets string
-  // from a point or not in the EphemeralKeyPairGenerator
-  UsePointCompression := True; // for compatibility
-
-  Result := TIESParameterSpec.Create(Derivation, Encoding, MacKeySizeInBits,
-    CipherKeySizeInBits, IVBytes, UsePointCompression);
+  LDerivation := nil;
+  LEncoding := nil;
+  System.SetLength(LIVBytes, 16); // Zero-initialized IV for PascalCoin compatibility
+  LMacKeySizeInBits := 32 * 8;
+  LCipherKeySizeInBits := 32 * 8;
+
+  LIesParams := TIesWithCipherParameters.Create(LDerivation, LEncoding,
+    LMacKeySizeInBits, LCipherKeySizeInBits);
+  Result := TParametersWithIV.Create(LIesParams, LIVBytes);
 end;
 
 function TTestPascalCoinECIES.GetECIESPascalCoinCompatibilityEngine
-  : IPascalCoinIESEngine;
+  : IPascalCoinIesEngine;
 var
-  cipher: IBufferedBlockCipher;
-  AesEngine: IAesEngine;
-  blockCipher: ICbcBlockCipher;
-  ECDHBasicAgreementInstance: IECDHBasicAgreement;
-  KDFInstance: IPascalCoinECIESKdfBytesGenerator;
-  DigestMACInstance: IMac;
-
+  LCipher: IBufferedBlockCipher;
+  LAesEngine: IAesEngine;
+  LBlockCipher: ICbcBlockCipher;
+  LECDHBasicAgreementInstance: IECDHBasicAgreement;
+  LKDFInstance: IPascalCoinECIESKdfBytesGenerator;
+  LDigestMACInstance: IMac;
 begin
   // Set up IES Cipher Engine For Compatibility With PascalCoin
 
-  ECDHBasicAgreementInstance := TECDHBasicAgreement.Create();
+  LECDHBasicAgreementInstance := TECDHBasicAgreement.Create();
 
-  KDFInstance := TPascalCoinECIESKdfBytesGenerator.Create
+  LKDFInstance := TPascalCoinECIESKdfBytesGenerator.Create
     (TDigestUtilities.GetDigest('SHA-512'));
 
-  DigestMACInstance := TMacUtilities.GetMac('HMAC-MD5');
+  LDigestMACInstance := TMacUtilities.GetMac('HMAC-MD5');
 
   // Set Up Block Cipher
-  AesEngine := TAesEngine.Create(); // AES Engine
+  LAesEngine := TAesEngine.Create(); // AES Engine
 
-  blockCipher := TCbcBlockCipher.Create(AesEngine); // CBC
+  LBlockCipher := TCbcBlockCipher.Create(LAesEngine); // CBC
 
-  cipher := TPaddedBufferedBlockCipher.Create(blockCipher,
+  LCipher := TPaddedBufferedBlockCipher.Create(LBlockCipher,
     TZeroBytePadding.Create() as IZeroBytePadding); // ZeroBytePadding
 
-  Result := TPascalCoinIESEngine.Create(ECDHBasicAgreementInstance, KDFInstance,
-    DigestMACInstance, cipher);
+  Result := TPascalCoinIesEngine.Create(LECDHBasicAgreementInstance, LKDFInstance,
+    LDigestMACInstance, LCipher);
 end;
 
 function TTestPascalCoinECIES.RecreatePublicKeyFromAffineXandAffineYCoord
-  (keyType: TKeyType; const RawAffineX, RawAffineY: TBytes)
+  (AKeyType: TKeyType; const RawAffineX, RawAffineY: TBytes)
   : IECPublicKeyParameters;
 var
   domain: IECDomainParameters;
@@ -205,7 +205,7 @@ var
   point: IECPoint;
   BigXCoord, BigYCoord: TBigInteger;
 begin
-  LCurve := GetCurveFromKeyType(keyType);
+  LCurve := GetCurveFromKeyType(AKeyType);
   domain := TECDomainParameters.Create(LCurve.Curve, LCurve.G, LCurve.N,
     LCurve.H, LCurve.GetSeed);
 
@@ -217,14 +217,14 @@ begin
   Result := TECPublicKeyParameters.Create('ECDSA', point, domain);
 end;
 
-function TTestPascalCoinECIES.RecreatePrivateKeyFromByteArray(keyType: TKeyType;
+function TTestPascalCoinECIES.RecreatePrivateKeyFromByteArray(AKeyType: TKeyType;
   const RawPrivateKey: TBytes): IECPrivateKeyParameters;
 var
   domain: IECDomainParameters;
   LCurve: IX9ECParameters;
   PrivD: TBigInteger;
 begin
-  LCurve := GetCurveFromKeyType(keyType);
+  LCurve := GetCurveFromKeyType(AKeyType);
   domain := TECDomainParameters.Create(LCurve.Curve, LCurve.G, LCurve.N,
     LCurve.H, LCurve.GetSeed);
 
@@ -233,65 +233,81 @@ begin
   Result := TECPrivateKeyParameters.Create('ECDSA', PrivD, domain);
 end;
 
-function TTestPascalCoinECIES.DoPascalCoinECIESEncrypt(keyType: TKeyType;
+function TTestPascalCoinECIES.DoPascalCoinECIESEncrypt(AKeyType: TKeyType;
   const RawAffineXCoord, RawAffineYCoord, PayloadToEncrypt: String): String;
 var
-  CipherEncrypt: IIESCipher;
+  LEngine: IIesEngine;
+  LCurve: IX9ECParameters;
+  LDomain: IECDomainParameters;
+  LGen: IECKeyPairGenerator;
+  LKeyGen: IEphemeralKeyPairGenerator;
+  LPlainBytes: TBytes;
 begin
-  // Encryption
-  CipherEncrypt := TIESCipher.Create(GetECIESPascalCoinCompatibilityEngine());
-  CipherEncrypt.Init(True, RecreatePublicKeyFromAffineXandAffineYCoord(keyType,
+  LEngine := GetECIESPascalCoinCompatibilityEngine() as IIesEngine;
+  LCurve := GetCurveFromKeyType(AKeyType);
+  LDomain := TECDomainParameters.Create(LCurve.Curve, LCurve.G, LCurve.N,
+    LCurve.H, LCurve.GetSeed);
+  LGen := TECKeyPairGenerator.Create();
+  LGen.Init(TECKeyGenerationParameters.Create(LDomain, FRandom));
+  LKeyGen := TEphemeralKeyPairGenerator.Create(LGen, TKeyEncoder.Create(True) as IKeyEncoder);
+  LEngine.Init(RecreatePublicKeyFromAffineXandAffineYCoord(AKeyType,
     DecodeHex(RawAffineXCoord), DecodeHex(RawAffineYCoord)),
-    GetPascalCoinIESParameterSpec(), FRandom);
-  Result := EncodeHex(CipherEncrypt.DoFinal(TConverters.ConvertStringToBytes
-    (PayloadToEncrypt, TEncoding.ASCII)));
+    GetPascalCoinIESParameters(), LKeyGen);
+  LPlainBytes := TConverters.ConvertStringToBytes(PayloadToEncrypt, TEncoding.ASCII);
+  Result := EncodeHex(LEngine.ProcessBlock(LPlainBytes, 0, System.Length(LPlainBytes)));
 end;
 
-function TTestPascalCoinECIES.DoPascalCoinECIESDecrypt(keyType: TKeyType;
+function TTestPascalCoinECIES.DoPascalCoinECIESDecrypt(AKeyType: TKeyType;
   const RawPrivateKey, PayloadToDecrypt: String): String;
 var
-  CipherDecrypt: IIESCipher;
+  LEngine: IIesEngine;
+  LCurve: IX9ECParameters;
+  LDomain: IECDomainParameters;
+  LParser: IKeyParser;
+  LCipherBytes: TBytes;
 begin
   try
-    // Decryption
-    CipherDecrypt := TIESCipher.Create(GetECIESPascalCoinCompatibilityEngine());
-    CipherDecrypt.Init(False, RecreatePrivateKeyFromByteArray(keyType,
-      DecodeHex(RawPrivateKey)), GetPascalCoinIESParameterSpec(), FRandom);
-
+    LEngine := GetECIESPascalCoinCompatibilityEngine() as IIesEngine;
+    LCurve := GetCurveFromKeyType(AKeyType);
+    LDomain := TECDomainParameters.Create(LCurve.Curve, LCurve.G, LCurve.N,
+      LCurve.H, LCurve.GetSeed);
+    LParser := TECIESPublicKeyParser.Create(LDomain) as IKeyParser;
+    LEngine.Init(RecreatePrivateKeyFromByteArray(AKeyType, DecodeHex(RawPrivateKey)),
+      GetPascalCoinIESParameters(), LParser);
+    LCipherBytes := DecodeHex(PayloadToDecrypt);
     Result := TConverters.ConvertBytesToString
-      (CipherDecrypt.DoFinal(DecodeHex(PayloadToDecrypt)), TEncoding.ASCII);
+      (LEngine.ProcessBlock(LCipherBytes, 0, System.Length(LCipherBytes)), TEncoding.ASCII);
   except
-    // should only happen if decryption fails
     raise;
   end;
 end;
 
-procedure TTestPascalCoinECIES.DoTestPascalCoinECIESDecrypt(const id: String;
-  keyType: TKeyType; const RawPrivateKey, PayloadToDecrypt,
+procedure TTestPascalCoinECIES.DoTestPascalCoinECIESDecrypt(const AId: String;
+  AKeyType: TKeyType; const RawPrivateKey, PayloadToDecrypt,
   ExpectedOutput: String);
 var
   DecryptedPayload: String;
 begin
-  DecryptedPayload := DoPascalCoinECIESDecrypt(keyType, RawPrivateKey,
+  DecryptedPayload := DoPascalCoinECIESDecrypt(AKeyType, RawPrivateKey,
     PayloadToDecrypt);
   CheckEquals(ExpectedOutput, DecryptedPayload,
-    Format('Test %s Failed, Expected "%s" but got "%s"', [id + '_Decrypt',
+    Format('Test %s Failed, Expected "%s" but got "%s"', [AId + '_Decrypt',
     ExpectedOutput, DecryptedPayload]));
 end;
 
 procedure TTestPascalCoinECIES.DoTestPascalCoinECIESEncryptDecrypt
-  (const id: String; keyType: TKeyType; const RawPrivateKey, RawAffineXCoord,
+  (const AId: String; AKeyType: TKeyType; const RawPrivateKey, RawAffineXCoord,
   RawAffineYCoord, PayloadToEncrypt: String);
 var
   ActualOutput: String;
 begin
-  ActualOutput := DoPascalCoinECIESDecrypt(keyType, RawPrivateKey,
-    DoPascalCoinECIESEncrypt(keyType, RawAffineXCoord, RawAffineYCoord,
+  ActualOutput := DoPascalCoinECIESDecrypt(AKeyType, RawPrivateKey,
+    DoPascalCoinECIESEncrypt(AKeyType, RawAffineXCoord, RawAffineYCoord,
     PayloadToEncrypt));
 
   CheckEquals(PayloadToEncrypt, ActualOutput,
     Format('Test %s Failed, Expected "%s" but got "%s"',
-    [id + '_EncryptDecrypt', PayloadToEncrypt, ActualOutput]));
+    [AId + '_EncryptDecrypt', PayloadToEncrypt, ActualOutput]));
 end;
 
 procedure TTestPascalCoinECIES.TestPacalCoinECIESDecrypt;

+ 194 - 0
CryptoLib/src/Crypto/Ciphers/ClpBufferedIesCipher.pas

@@ -0,0 +1,194 @@
+{ *********************************************************************************** }
+{ *                              CryptoLib Library                                  * }
+{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
+{ *                 Github Repository <https://github.com/Xor-el>                   * }
+
+{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
+{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
+
+{ *                              Acknowledgements:                                  * }
+{ *                                                                                 * }
+{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
+{ *                           development of this library                           * }
+
+{ * ******************************************************************************* * }
+
+(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
+
+unit ClpBufferedIesCipher;
+
+{$I ..\..\Include\CryptoLib.inc}
+
+interface
+
+uses
+  Math,
+  SysUtils,
+  ClpIBufferedCipher,
+  ClpIBufferedCipherBase,
+  ClpICipherParameters,
+  ClpIIESEngine,
+  ClpIIESParameters,
+  ClpIIesCipherParameters,
+  ClpBufferedCipherBase,
+  ClpCryptoLibTypes;
+
+resourcestring
+  SEngineNil = 'Engine Cannot be Nil';
+  SCipherNotInitialised = 'Cipher not initialised';
+  SIesCipherParametersRequired = 'IIesCipherParameters required for Init';
+
+type
+  TBufferedIesCipher = class sealed(TBufferedCipherBase)
+
+  strict private
+  var
+    FEngine: IIesEngine;
+    FForEncryption: Boolean;
+    FBuffer: TCryptoLibByteArray;
+    FBufferLen: Int32;
+
+  strict protected
+    function GetAlgorithmName: String; override;
+
+  public
+    constructor Create(const AEngine: IIesEngine);
+
+    procedure Init(AForEncryption: Boolean;
+      const AParameters: ICipherParameters); override;
+
+    function GetBlockSize(): Int32; override;
+    function GetOutputSize(AInputLen: Int32): Int32; override;
+    function GetUpdateOutputSize(AInputLen: Int32): Int32; override;
+
+    function ProcessByte(AInput: Byte): TCryptoLibByteArray; override;
+    function ProcessBytes(const AInput: TCryptoLibByteArray; AInOff,
+      ALength: Int32): TCryptoLibByteArray; override;
+
+    function DoFinal(): TCryptoLibByteArray; override;
+    function DoFinal(const AInput: TCryptoLibByteArray; AInOff,
+      ALength: Int32): TCryptoLibByteArray; override;
+
+    procedure Reset(); override;
+  end;
+
+implementation
+
+const
+  SIESAlgorithmName = 'IES';
+  SDefaultMacSize = 20;
+
+{ TBufferedIesCipher }
+
+constructor TBufferedIesCipher.Create(const AEngine: IIesEngine);
+begin
+  Inherited Create();
+  if AEngine = Nil then
+    raise EArgumentNilCryptoLibException.CreateRes(@SEngineNil);
+  FEngine := AEngine;
+  FBufferLen := 0;
+end;
+
+procedure TBufferedIesCipher.Init(AForEncryption: Boolean;
+  const AParameters: ICipherParameters);
+var
+  LParams: IIesCipherParameters;
+  LPriv, LPub: ICipherParameters;
+  LIesParams: IIesParameters;
+begin
+  FForEncryption := AForEncryption;
+  if AParameters = Nil then
+    raise EArgumentNilCryptoLibException.CreateRes(@SIesCipherParametersRequired);
+  if not Supports(AParameters, IIesCipherParameters, LParams) then
+    raise EArgumentCryptoLibException.CreateRes(@SIesCipherParametersRequired);
+  LPriv := LParams.PrivateKey;
+  LPub := LParams.PublicKey;
+  LIesParams := LParams.IesParameters;
+  FEngine.Init(AForEncryption, LPriv, LPub, LIesParams);
+  FBufferLen := 0;
+end;
+
+function TBufferedIesCipher.GetAlgorithmName: String;
+begin
+  Result := SIESAlgorithmName;
+end;
+
+function TBufferedIesCipher.GetBlockSize: Int32;
+begin
+  Result := 0;
+end;
+
+function TBufferedIesCipher.GetOutputSize(AInputLen: Int32): Int32;
+var
+  LBaseLen: Int32;
+begin
+  if FEngine = Nil then
+    raise EInvalidOperationCryptoLibException.CreateRes(@SCipherNotInitialised);
+  LBaseLen := AInputLen + FBufferLen;
+  if FForEncryption then
+    Result := LBaseLen + SDefaultMacSize
+  else
+    Result := LBaseLen - SDefaultMacSize;
+  if Result < 0 then
+    Result := 0;
+end;
+
+function TBufferedIesCipher.GetUpdateOutputSize(AInputLen: Int32): Int32;
+begin
+  Result := 0;
+end;
+
+function TBufferedIesCipher.ProcessByte(AInput: Byte): TCryptoLibByteArray;
+begin
+  if FBufferLen >= System.Length(FBuffer) then
+    System.SetLength(FBuffer, Math.Max(256, FBufferLen * 2));
+  FBuffer[FBufferLen] := AInput;
+  System.Inc(FBufferLen);
+  Result := Nil;
+end;
+
+function TBufferedIesCipher.ProcessBytes(const AInput: TCryptoLibByteArray;
+  AInOff, ALength: Int32): TCryptoLibByteArray;
+var
+  LNewLen: Int32;
+begin
+  if AInput = Nil then
+    raise EArgumentNilCryptoLibException.Create('input');
+  if (AInOff < 0) or (ALength < 0) or
+    (AInOff + ALength > System.Length(AInput)) then
+    raise EArgumentCryptoLibException.Create('invalid offset/length');
+  if ALength = 0 then
+  begin
+    Result := Nil;
+    Exit;
+  end;
+  LNewLen := FBufferLen + ALength;
+  if LNewLen > System.Length(FBuffer) then
+    System.SetLength(FBuffer, LNewLen);
+  System.Move(AInput[AInOff], FBuffer[FBufferLen], ALength * System.SizeOf(Byte));
+  FBufferLen := LNewLen;
+  Result := Nil;
+end;
+
+function TBufferedIesCipher.DoFinal: TCryptoLibByteArray;
+var
+  LBlock: TCryptoLibByteArray;
+begin
+  LBlock := FEngine.ProcessBlock(FBuffer, 0, FBufferLen);
+  Reset();
+  Result := LBlock;
+end;
+
+function TBufferedIesCipher.DoFinal(const AInput: TCryptoLibByteArray; AInOff,
+  ALength: Int32): TCryptoLibByteArray;
+begin
+  ProcessBytes(AInput, AInOff, ALength);
+  Result := DoFinal();
+end;
+
+procedure TBufferedIesCipher.Reset;
+begin
+  FBufferLen := 0;
+end;
+
+end.

+ 21 - 1
CryptoLib/src/Crypto/Ciphers/ClpCipherUtilities.pas

@@ -69,7 +69,16 @@ uses
   ClpIISO9796d1Encoding,
   ClpRsaBlindedEngine,
   ClpIRsaBlindedEngine,
-  ClpIAsymmetricBlockCipher;
+  ClpIAsymmetricBlockCipher,
+  ClpBufferedIesCipher,
+  ClpIESEngine,
+  ClpIIESEngine,
+  ClpECDHBasicAgreement,
+  ClpIECDHBasicAgreement,
+  ClpKdf2BytesGenerator,
+  ClpIKdf2BytesGenerator,
+  ClpHMac,
+  ClpIHMac;
 
 resourcestring
   SMechanismNil = 'Mechanism Cannot be Nil';
@@ -262,6 +271,17 @@ var
   LPadding: IBlockCipherPadding;
 begin
   Result := nil;
+
+  if UpperCase(AMechanism) = 'ECIES' then
+  begin
+    Result := TBufferedIesCipher.Create(TIesEngine.Create(
+      TECDHBasicAgreement.Create() as IECDHBasicAgreement,
+      TKdf2BytesGenerator.Create(TDigestUtilities.GetDigest('SHA-1'))
+        as IKdf2BytesGenerator,
+      THMac.Create(TDigestUtilities.GetDigest('SHA-1')) as IHMac));
+    Exit;
+  end;
+
   LParts := TStringUtilities.SplitString(AMechanism, '/');
   if System.Length(LParts) < 1 then
     Exit;

+ 0 - 300
CryptoLib/src/Crypto/Ciphers/ClpIESCipher.pas

@@ -1,300 +0,0 @@
-{ *********************************************************************************** }
-{ *                              CryptoLib Library                                  * }
-{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
-{ *                 Github Repository <https://github.com/Xor-el>                   * }
-
-{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
-{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
-
-{ *                              Acknowledgements:                                  * }
-{ *                                                                                 * }
-{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
-{ *                           development of this library                           * }
-
-{ * ******************************************************************************* * }
-
-(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
-
-unit ClpIESCipher;
-
-{$I ..\..\Include\CryptoLib.inc}
-
-interface
-
-uses
-  Classes,
-  SysUtils,
-  ClpIIESEngine,
-  ClpIECIESPublicKeyParser,
-  ClpECIESPublicKeyParser,
-  ClpIAsymmetricKeyParameter,
-  ClpIAlgorithmParameterSpec,
-  ClpIIESParameterSpec,
-  ClpICipherParameters,
-  ClpIParametersWithRandom,
-  ClpIECKeyParameters,
-  ClpIESWithCipherParameters,
-  ClpIECDomainParameters,
-  ClpIECKeyPairGenerator,
-  ClpECKeyPairGenerator,
-  ClpECKeyGenerationParameters,
-  ClpIECKeyGenerationParameters,
-  ClpEphemeralKeyPairGenerator,
-  ClpIEphemeralKeyPairGenerator,
-  ClpParametersWithIV,
-  ClpIIESCipher,
-  ClpKeyEncoder,
-  ClpIKeyEncoder,
-  ClpISecureRandom,
-  ClpCryptoLibTypes;
-
-resourcestring
-  SInvalidPublicKey =
-    'Must be Passed Recipient''s Public EC Key for Encryption';
-  SInvalidPrivateKey =
-    'Must be Passed Recipient''s Private EC Key for Decryption';
-  SIAlgorithmParameterSpecNil = 'Parameter Spec Cannot Be Nil';
-  SUnableToProcessBlock = 'Unable to Process Block. "%s"';
-  SIESParameterSpecError = 'Must be Passed IES Parameter Spec';
-  SNonceInvalidLength = 'Nonce in IES Parameters Needs to be "%s" Bytes Long';
-
-type
-  TIESCipher = class sealed(TInterfacedObject, IIESCipher)
-
-  strict private
-  var
-    FivLength: Int32;
-    FEngine: IIESEngine;
-    FForEncryption: Boolean;
-    FBuffer: TMemoryStream;
-    FEngineSpec: IIESParameterSpec;
-    Fkey: IAsymmetricKeyParameter;
-    FRandom: ISecureRandom;
-
-    function Aggregate: TCryptoLibByteArray; inline;
-
-  public
-    procedure Init(ForEncryption: Boolean; const Key: ICipherParameters;
-      const EngineSpec: IAlgorithmParameterSpec; const Random: ISecureRandom);
-
-    procedure ProcessBytes(const input: TCryptoLibByteArray); overload;
-    procedure ProcessBytes(const input: TCryptoLibByteArray;
-      inputOffset, inputLen: Int32); overload;
-
-    function DoFinal(const input: TCryptoLibByteArray)
-      : TCryptoLibByteArray; overload;
-
-    function DoFinal(const input: TCryptoLibByteArray;
-      inputOffset, inputLen: Int32): TCryptoLibByteArray; overload;
-
-    function DoFinal(const input: TCryptoLibByteArray;
-      inputOffset, inputLen: Int32; const output: TCryptoLibByteArray;
-      outputOffset: Int32): Int32; overload;
-
-    constructor Create(const Engine: IIESEngine; ivLength: Int32 = 0);
-    destructor Destroy(); override;
-
-  end;
-
-implementation
-
-{ TIESCipher }
-
-function TIESCipher.Aggregate: TCryptoLibByteArray;
-begin
-  Result := Nil;
-  if FBuffer.Size > 0 then
-  begin
-    FBuffer.Position := 0;
-    System.SetLength(Result, FBuffer.Size);
-    FBuffer.Read(Result[0], FBuffer.Size);
-  end;
-end;
-
-constructor TIESCipher.Create(const Engine: IIESEngine; ivLength: Int32);
-begin
-  Inherited Create();
-  FEngine := Engine;
-  FivLength := ivLength;
-  FBuffer := TMemoryStream.Create();
-end;
-
-function TIESCipher.DoFinal(const input: TCryptoLibByteArray;
-  inputOffset, inputLen: Int32): TCryptoLibByteArray;
-var
-  &in: TCryptoLibByteArray;
-  params: ICipherParameters;
-  ecParams: IECDomainParameters;
-  gen: IECKeyPairGenerator;
-  kGen: IEphemeralKeyPairGenerator;
-  UsePointCompression: Boolean;
-begin
-  if (inputLen <> 0) then
-  begin
-    FBuffer.Write(input[inputOffset], inputLen);
-  end;
-
-  &in := Aggregate();
-  FBuffer.Clear;
-  FBuffer.SetSize(Int64(0));
-
-  // Convert parameters for use in IESEngine
-  params := TIESWithCipherParameters.Create(FEngineSpec.GetDerivationV,
-    FEngineSpec.GetEncodingV, FEngineSpec.MacKeySize,
-    FEngineSpec.CipherKeySize);
-
-  if (FEngineSpec.Nonce <> Nil) then
-  begin
-    params := TParametersWithIV.Create(params, FEngineSpec.Nonce);
-  end;
-  ecParams := (Fkey as IECKeyParameters).Parameters;
-
-  if FForEncryption then
-  begin
-    // Generate the ephemeral key pair
-    gen := TECKeyPairGenerator.Create();
-    gen.Init(TECKeyGenerationParameters.Create(ecParams, FRandom)
-      as IECKeyGenerationParameters);
-
-    UsePointCompression := FEngineSpec.PointCompression;
-
-    kGen := TEphemeralKeyPairGenerator.Create(gen,
-      TKeyEncoder.Create(UsePointCompression) as IKeyEncoder);
-
-    // Encrypt the buffer
-
-    try
-      FEngine.Init(Fkey, params, kGen);
-
-      Result := FEngine.ProcessBlock(&in, 0, System.length(&in));
-      Exit;
-    except
-      on e: Exception do
-      begin
-        raise EBadBlockCryptoLibException.CreateResFmt(@SUnableToProcessBlock,
-          [e.Message]);
-      end;
-    end;
-  end
-  else
-  begin
-    // Decrypt the buffer
-
-    try
-      FEngine.Init(Fkey, params, TECIESPublicKeyParser.Create(ecParams)
-        as IECIESPublicKeyParser);
-
-      Result := FEngine.ProcessBlock(&in, 0, System.length(&in));
-      Exit;
-    except
-      on e: EInvalidCipherTextCryptoLibException do
-      begin
-        raise EBadBlockCryptoLibException.CreateResFmt(@SUnableToProcessBlock,
-          [e.Message]);
-      end;
-    end;
-  end;
-
-end;
-
-destructor TIESCipher.Destroy;
-begin
-  FBuffer.Free;
-  inherited Destroy;
-end;
-
-function TIESCipher.DoFinal(const input: TCryptoLibByteArray)
-  : TCryptoLibByteArray;
-begin
-  Result := DoFinal(input, 0, System.length(input));
-end;
-
-function TIESCipher.DoFinal(const input: TCryptoLibByteArray;
-  inputOffset, inputLen: Int32; const output: TCryptoLibByteArray;
-  outputOffset: Int32): Int32;
-var
-  buf: TCryptoLibByteArray;
-begin
-  buf := DoFinal(input, inputOffset, inputLen);
-  System.Move(buf[0], output[outputOffset], System.length(buf) *
-    System.SizeOf(Byte));
-  Result := System.length(buf);
-end;
-
-procedure TIESCipher.Init(ForEncryption: Boolean; const Key: ICipherParameters;
-  const EngineSpec: IAlgorithmParameterSpec; const Random: ISecureRandom);
-var
-  LKey: ICipherParameters;
-  Nonce: TCryptoLibByteArray;
-begin
-
-  FForEncryption := ForEncryption;
-
-  if (EngineSpec = Nil) then
-  begin
-    raise EArgumentNilCryptoLibException.CreateRes
-      (@SIAlgorithmParameterSpecNil);
-  end
-  else if (Supports(EngineSpec, IIESParameterSpec)) then
-  begin
-    FEngineSpec := EngineSpec as IIESParameterSpec;
-  end
-  else
-  begin
-    raise EInvalidParameterCryptoLibException.CreateRes
-      (@SIESParameterSpecError);
-  end;
-
-  Nonce := FEngineSpec.Nonce;
-
-  if ((FivLength <> 0) and ((Nonce = Nil) or (System.length(Nonce) <>
-    FivLength))) then
-  begin
-    raise EInvalidParameterCryptoLibException.CreateResFmt(@SNonceInvalidLength,
-      [FivLength]);
-  end;
-
-  LKey := Key;
-
-  // Parse the recipient's key
-  if ForEncryption then
-  begin
-    if ((not Supports(LKey, IAsymmetricKeyParameter, Fkey)) or
-      ((Fkey.IsPrivate))) then
-    begin
-      raise EInvalidKeyCryptoLibException.CreateRes(@SInvalidPublicKey);
-    end;
-
-  end
-  else
-  begin
-    if Supports(LKey, IParametersWithRandom) then
-    begin
-      LKey := (LKey as IParametersWithRandom).Parameters;
-    end;
-
-    if ((not Supports(LKey, IAsymmetricKeyParameter, Fkey)) or
-      (not(Fkey.IsPrivate))) then
-    begin
-      raise EInvalidKeyCryptoLibException.CreateRes(@SInvalidPrivateKey);
-    end;
-
-  end;
-
-  FRandom := Random;
-  FBuffer.Clear;
-  FBuffer.SetSize(Int64(0));
-end;
-
-procedure TIESCipher.ProcessBytes(const input: TCryptoLibByteArray);
-begin
-  ProcessBytes(input, 0, System.length(input));
-end;
-
-procedure TIESCipher.ProcessBytes(const input: TCryptoLibByteArray;
-  inputOffset, inputLen: Int32);
-begin
-  FBuffer.Write(input[inputOffset], inputLen);
-end;
-
-end.

+ 0 - 636
CryptoLib/src/Crypto/Engines/ClpIESEngine.pas

@@ -1,636 +0,0 @@
-{ *********************************************************************************** }
-{ *                              CryptoLib Library                                  * }
-{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
-{ *                 Github Repository <https://github.com/Xor-el>                   * }
-
-{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
-{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
-
-{ *                              Acknowledgements:                                  * }
-{ *                                                                                 * }
-{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
-{ *                           development of this library                           * }
-
-{ * ******************************************************************************* * }
-
-(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
-
-unit ClpIESEngine;
-
-{$I ..\..\Include\CryptoLib.inc}
-
-interface
-
-uses
-  Classes,
-  SysUtils,
-  ClpIMac,
-  ClpIIESEngine,
-  ClpIBasicAgreement,
-  ClpIDerivationFunction,
-  ClpIBufferedBlockCipher,
-  ClpICipherParameters,
-  ClpIIESParameters,
-  ClpIEphemeralKeyPairGenerator,
-  ClpIAsymmetricKeyParameter,
-  ClpKeyParameter,
-  ClpIKeyParameter,
-  ClpParametersWithIV,
-  ClpIParametersWithIV,
-  ClpIKeyParser,
-  ClpIEphemeralKeyPair,
-  ClpKdfParameters,
-  ClpIKdfParameters,
-  ClpIIESWithCipherParameters,
-  ClpConverters,
-  ClpArrayUtilities,
-  ClpBigInteger,
-  ClpBigIntegers,
-  ClpCryptoLibTypes;
-
-resourcestring
-  SErrorRecoveringEphemeralPublicKey =
-    'Unable to Recover Ephemeral Public Key: "%s"';
-  SInvalidCipherTextLength =
-    'Length of Input Must be Greater than the MAC and V Combined';
-  SInvalidMAC = 'Invalid MAC';
-
-type
-
-  /// <summary>
-  /// Support class for constructing integrated encryption ciphers for doing
-  /// basic message exchanges on top of key agreement ciphers. <br />Follows
-  /// the description given in IEEE Std 1363a.
-  /// </summary>
-  TIESEngine = class(TInterfacedObject, IIESEngine)
-
-  strict private
-  var
-    Fparam: IIESParameters;
-
-    // as described in Shroup's paper( ch 10, pg 20) and P1363a
-    function GetLengthTag(const p2: TCryptoLibByteArray)
-      : TCryptoLibByteArray; inline;
-
-    procedure ExtractParams(const params: ICipherParameters); inline;
-
-    function SimilarMacCompute(const ArgOne, ArgTwo: TCryptoLibByteArray)
-      : TCryptoLibByteArray; inline;
-
-  strict protected
-
-  var
-    Fagree: IBasicAgreement;
-    Fkdf: IDerivationFunction;
-    Fmac: IMac;
-    Fcipher: IBufferedBlockCipher;
-    FV, FIV: TCryptoLibByteArray;
-    FforEncryption: Boolean;
-    FprivParam, FpubParam: ICipherParameters;
-    FkeyPairGenerator: IEphemeralKeyPairGenerator;
-    FkeyParser: IKeyParser;
-
-    function GetCipher: IBufferedBlockCipher; inline;
-    function GetMac: IMac; inline;
-    procedure SetupBlockCipherAndMacKeyBytes(out K1,
-      K2: TCryptoLibByteArray); inline;
-
-    function EncryptBlock(const &in: TCryptoLibByteArray; inOff, inLen: Int32)
-      : TCryptoLibByteArray; virtual;
-
-    function DecryptBlock(const in_enc: TCryptoLibByteArray;
-      inOff, inLen: Int32): TCryptoLibByteArray; virtual;
-
-  public
-
-    /// <summary>
-    /// Set up for use with stream mode, where the key derivation function is
-    /// used to provide a stream of bytes to xor with the message.
-    /// </summary>
-    /// <param name="agree">
-    /// the key agreement used as the basis for the encryption
-    /// </param>
-    /// <param name="kdf">
-    /// the key derivation function used for byte generation
-    /// </param>
-    /// <param name="mac">
-    /// the message authentication code generator for the message
-    /// </param>
-    constructor Create(const agree: IBasicAgreement;
-      const kdf: IDerivationFunction; const mac: IMac); overload;
-
-    /// <summary>
-    /// Set up for use in conjunction with a block cipher to handle the <br />
-    /// message. It is <b>strongly</b> recommended that the cipher is not
-    /// in ECB mode.
-    /// </summary>
-    /// <param name="agree">
-    /// the key agreement used as the basis for the encryption
-    /// </param>
-    /// <param name="kdf">
-    /// the key derivation function used for byte generation
-    /// </param>
-    /// <param name="mac">
-    /// the message authentication code generator for the message
-    /// </param>
-    /// <param name="cipher">
-    /// the cipher to used for encrypting the message
-    /// </param>
-    constructor Create(const agree: IBasicAgreement;
-      const kdf: IDerivationFunction; const mac: IMac;
-      const cipher: IBufferedBlockCipher); overload;
-
-    /// <summary>
-    /// Initialise the encryptor/decryptor.
-    /// </summary>
-    /// <param name="forEncryption">
-    /// whether or not this is encryption/decryption.
-    /// </param>
-    /// <param name="privParam">
-    /// our private key parameters
-    /// </param>
-    /// <param name="pubParam">
-    /// the recipient's/sender's public key parameters
-    /// </param>
-    /// <param name="params">
-    /// encoding and derivation parameters, may be wrapped to include an IV
-    /// for an underlying block cipher.
-    /// </param>
-    procedure Init(forEncryption: Boolean; const privParam, pubParam,
-      params: ICipherParameters); overload;
-
-    /// <summary>
-    /// Initialise the encryptor.
-    /// </summary>
-    /// <param name="publicKey">
-    /// the recipient's/sender's public key parameters
-    /// </param>
-    /// <param name="params">
-    /// encoding and derivation parameters, may be wrapped to include an IV
-    /// for an underlying block cipher.
-    /// </param>
-    /// <param name="ephemeralKeyPairGenerator">
-    /// the ephemeral key pair generator to use.
-    /// </param>
-    procedure Init(const publicKey: IAsymmetricKeyParameter;
-      const params: ICipherParameters;
-      const ephemeralKeyPairGenerator: IEphemeralKeyPairGenerator); overload;
-
-    /// <summary>
-    /// Initialise the decryptor.
-    /// </summary>
-    /// <param name="privateKey">
-    /// the recipient's private key.
-    /// </param>
-    /// <param name="params">
-    /// encoding and derivation parameters, may be wrapped to include an IV
-    /// for an underlying block cipher.
-    /// </param>
-    /// <param name="publicKeyParser">
-    /// the parser for reading the ephemeral public key.
-    /// </param>
-    procedure Init(const privateKey: IAsymmetricKeyParameter;
-      const params: ICipherParameters;
-      const publicKeyParser: IKeyParser); overload;
-
-    function ProcessBlock(const &in: TCryptoLibByteArray; inOff, inLen: Int32)
-      : TCryptoLibByteArray; virtual;
-
-    property cipher: IBufferedBlockCipher read GetCipher;
-    property mac: IMac read GetMac;
-
-  end;
-
-implementation
-
-{ TIESEngine }
-
-function TIESEngine.GetLengthTag(const p2: TCryptoLibByteArray)
-  : TCryptoLibByteArray;
-begin
-  System.SetLength(Result, 8);
-  if (p2 <> Nil) then
-  begin
-    TConverters.ReadUInt64AsBytesBE(System.Length(p2) * 8, Result, 0);
-  end;
-end;
-
-function TIESEngine.SimilarMacCompute(const ArgOne, ArgTwo: TCryptoLibByteArray)
-  : TCryptoLibByteArray;
-begin
-  if (ArgOne <> Nil) then
-  begin
-    Fmac.BlockUpdate(ArgOne, 0, System.Length(ArgOne));
-  end;
-  if (System.Length(FV) <> 0) then
-  begin
-    Fmac.BlockUpdate(ArgTwo, 0, System.Length(ArgTwo));
-  end;
-  Result := Fmac.DoFinal;
-end;
-
-procedure TIESEngine.SetupBlockCipherAndMacKeyBytes(out K1,
-  K2: TCryptoLibByteArray);
-var
-  K: TCryptoLibByteArray;
-begin
-  System.SetLength(K1, (Fparam as IIESWithCipherParameters)
-    .CipherKeySize div 8);
-  System.SetLength(K2, Fparam.MacKeySize div 8);
-  System.SetLength(K, System.Length(K1) + System.Length(K2));
-
-  Fkdf.GenerateBytes(K, 0, System.Length(K));
-
-  System.Move(K[0], K1[0], System.Length(K1) * System.SizeOf(Byte));
-  System.Move(K[System.Length(K1)], K2[0], System.Length(K2) *
-    System.SizeOf(Byte));
-end;
-
-constructor TIESEngine.Create(const agree: IBasicAgreement;
-  const kdf: IDerivationFunction; const mac: IMac);
-begin
-  Inherited Create();
-  Fagree := agree;
-  Fkdf := kdf;
-  Fmac := mac;
-  Fcipher := Nil;
-end;
-
-constructor TIESEngine.Create(const agree: IBasicAgreement;
-  const kdf: IDerivationFunction; const mac: IMac;
-  const cipher: IBufferedBlockCipher);
-begin
-  Inherited Create();
-  Fagree := agree;
-  Fkdf := kdf;
-  Fmac := mac;
-  Fcipher := cipher;
-end;
-
-function TIESEngine.DecryptBlock(const in_enc: TCryptoLibByteArray;
-  inOff, inLen: Int32): TCryptoLibByteArray;
-var
-  M, K, K1, K2, p2, L2, T1, T2: TCryptoLibByteArray;
-  len, i, endPoint: Int32;
-  cp: ICipherParameters;
-begin
-  len := 0;
-  // Ensure that the length of the input is greater than the MAC in bytes
-  if (inLen < (System.Length(FV) + Fmac.GetMacSize)) then
-  begin
-    raise EInvalidCipherTextCryptoLibException.CreateRes
-      (@SInvalidCipherTextLength);
-  end;
-  // note order is important: set up keys, do simple encryptions, check mac, do final encryption.
-  if (Fcipher = Nil) then
-  begin
-
-    // Streaming mode.
-    System.SetLength(K1, inLen - System.Length(FV) - Fmac.GetMacSize);
-    System.SetLength(K2, Fparam.MacKeySize div 8);
-    System.SetLength(K, System.Length(K1) + System.Length(K2));
-
-    Fkdf.GenerateBytes(K, 0, System.Length(K));
-
-    if (System.Length(FV) <> 0) then
-    begin
-      System.Move(K[0], K2[0], System.Length(K2) * System.SizeOf(Byte));
-      if K1 <> Nil then
-      begin
-        System.Move(K[System.Length(K2)], K1[0],
-          System.Length(K1) * System.SizeOf(Byte));
-      end;
-    end
-    else
-    begin
-      if K1 <> Nil then
-      begin
-        System.Move(K[0], K1[0], System.Length(K1) * System.SizeOf(Byte));
-      end;
-      System.Move(K[System.Length(K1)], K2[0], System.Length(K2) *
-        System.SizeOf(Byte));
-    end;
-
-    // process the message
-    System.SetLength(M, System.Length(K1));
-
-    i := 0;
-
-    while i <> System.Length(K1) do
-    begin
-      M[i] := Byte(in_enc[inOff + System.Length(FV) + i] xor K1[i]);
-      System.Inc(i);
-    end;
-
-  end
-  else
-  begin
-    // Block cipher mode.
-
-    SetupBlockCipherAndMacKeyBytes(K1, K2);
-
-    cp := TKeyParameter.Create(K1);
-
-    // If iv is provided use it to initialise the cipher
-    if (FIV <> Nil) then
-    begin
-      cp := TParametersWithIV.Create(cp, FIV);
-    end;
-
-    Fcipher.Init(False, cp);
-
-    System.SetLength(M, Fcipher.GetOutputSize(inLen - System.Length(FV) -
-      Fmac.GetMacSize));
-
-    // do initial processing
-    len := Fcipher.ProcessBytes(in_enc, inOff + System.Length(FV),
-      inLen - System.Length(FV) - Fmac.GetMacSize, M, 0);
-
-  end;
-
-  // Convert the length of the encoding vector into a byte array.
-  p2 := Fparam.GetEncodingV();
-  L2 := Nil;
-  if (System.Length(FV) <> 0) then
-  begin
-    L2 := GetLengthTag(p2);
-  end;
-
-  // Verify the MAC.
-  endPoint := inOff + inLen;
-  T1 := TArrayUtilities.CopyOfRange<Byte>(in_enc, endPoint - Fmac.GetMacSize, endPoint);
-  System.SetLength(T2, System.Length(T1));
-
-  Fmac.Init((TKeyParameter.Create(K2) as IKeyParameter) as ICipherParameters);
-
-  Fmac.BlockUpdate(in_enc, inOff + System.Length(FV), inLen - System.Length(FV)
-    - System.Length(T2));
-
-  T2 := SimilarMacCompute(p2, L2);
-
-  if not TArrayUtilities.FixedTimeEquals(T1, T2) then
-  begin
-    raise EInvalidCipherTextCryptoLibException.CreateRes(@SInvalidMAC);
-  end;
-
-  if (Fcipher = Nil) then
-  begin
-    Result := M;
-    Exit;
-  end
-  else
-  begin
-    len := len + Fcipher.DoFinal(M, len);
-
-    Result := TArrayUtilities.CopyOfRange<Byte>(M, 0, len);
-    Exit;
-  end;
-end;
-
-function TIESEngine.EncryptBlock(const &in: TCryptoLibByteArray;
-  inOff, inLen: Int32): TCryptoLibByteArray;
-var
-  C, K, K1, K2, p2, L2, T: TCryptoLibByteArray;
-  len, i, lenCount: Int32;
-begin
-  if (Fcipher = Nil) then
-  begin
-    // Streaming mode.
-    System.SetLength(K1, inLen);
-    System.SetLength(K2, Fparam.MacKeySize div 8);
-    System.SetLength(K, System.Length(K1) + System.Length(K2));
-
-    Fkdf.GenerateBytes(K, 0, System.Length(K));
-
-    if (System.Length(FV) <> 0) then
-    begin
-      System.Move(K[0], K2[0], System.Length(K2) * System.SizeOf(Byte));
-      if K1 <> Nil then
-      begin
-        System.Move(K[System.Length(K2)], K1[0],
-          System.Length(K1) * System.SizeOf(Byte));
-      end;
-    end
-    else
-    begin
-      if K1 <> Nil then
-      begin
-        System.Move(K[0], K1[0], System.Length(K1) * System.SizeOf(Byte));
-      end;
-      System.Move(K[inLen], K2[0], System.Length(K2) * System.SizeOf(Byte));
-    end;
-
-    System.SetLength(C, inLen);
-
-    i := 0;
-
-    while i <> inLen do
-    begin
-      C[i] := Byte(&in[inOff + i] xor K1[i]);
-      System.Inc(i);
-    end;
-
-    len := inLen;
-  end
-  else
-  begin
-    // Block cipher mode.
-
-    SetupBlockCipherAndMacKeyBytes(K1, K2);
-
-    // If iv is provided use it to initialise the cipher
-    if (FIV <> Nil) then
-    begin
-      Fcipher.Init(true, TParametersWithIV.Create(TKeyParameter.Create(K1)
-        as IKeyParameter, FIV) as IParametersWithIV);
-    end
-    else
-    begin
-      Fcipher.Init(true, TKeyParameter.Create(K1) as IKeyParameter);
-    end;
-
-    System.SetLength(C, Fcipher.GetOutputSize(inLen));
-
-    len := Fcipher.ProcessBytes(&in, inOff, inLen, C, 0);
-    len := len + Fcipher.DoFinal(C, len);
-  end;
-
-  // Convert the length of the encoding vector into a byte array.
-  p2 := Fparam.GetEncodingV();
-  L2 := Nil;
-  if (System.Length(FV) <> 0) then
-  begin
-    L2 := GetLengthTag(p2);
-  end;
-
-  // Apply the MAC.
-  System.SetLength(T, Fmac.GetMacSize);
-
-  Fmac.Init((TKeyParameter.Create(K2) as IKeyParameter) as ICipherParameters);
-  Fmac.BlockUpdate(C, 0, System.Length(C));
-
-  T := SimilarMacCompute(p2, L2);
-
-  // Output the triple (V,C,T).
-  // V := Ephermeral Public Key
-  // C := Encrypted Payload
-  // T := Authentication Message (MAC)
-  System.SetLength(Result, System.Length(FV) + len + System.Length(T));
-  if FV <> Nil then
-  begin
-    System.Move(FV[0], Result[0], System.Length(FV) * System.SizeOf(Byte));
-  end;
-  lenCount := len * System.SizeOf(Byte);
-  if lenCount > 0 then
-  begin
-    System.Move(C[0], Result[System.Length(FV)], lenCount);
-  end;
-  System.Move(T[0], Result[System.Length(FV) + len],
-    System.Length(T) * System.SizeOf(Byte));
-
-end;
-
-procedure TIESEngine.ExtractParams(const params: ICipherParameters);
-begin
-  if Supports(params, IParametersWithIV) then
-  begin
-    FIV := (params as IParametersWithIV).GetIV;
-    Fparam := ((params as IParametersWithIV).Parameters) as IIESParameters;
-  end
-  else
-  begin
-    FIV := Nil;
-    Fparam := (params as IIESParameters);
-  end;
-end;
-
-function TIESEngine.GetCipher: IBufferedBlockCipher;
-begin
-  Result := Fcipher;
-end;
-
-function TIESEngine.GetMac: IMac;
-begin
-  Result := Fmac;
-end;
-
-procedure TIESEngine.Init(const privateKey: IAsymmetricKeyParameter;
-  const params: ICipherParameters; const publicKeyParser: IKeyParser);
-begin
-  FforEncryption := False;
-  FprivParam := privateKey;
-  FkeyParser := publicKeyParser;
-  ExtractParams(params);
-end;
-
-procedure TIESEngine.Init(const publicKey: IAsymmetricKeyParameter;
-  const params: ICipherParameters;
-  const ephemeralKeyPairGenerator: IEphemeralKeyPairGenerator);
-begin
-  FforEncryption := true;
-  FpubParam := publicKey;
-  FkeyPairGenerator := ephemeralKeyPairGenerator;
-  ExtractParams(params);
-end;
-
-procedure TIESEngine.Init(forEncryption: Boolean;
-  const privParam, pubParam, params: ICipherParameters);
-begin
-  FforEncryption := forEncryption;
-  FprivParam := privParam;
-  FpubParam := pubParam;
-  System.SetLength(FV, 0);
-  ExtractParams(params);
-end;
-
-function TIESEngine.ProcessBlock(const &in: TCryptoLibByteArray;
-  inOff, inLen: Int32): TCryptoLibByteArray;
-var
-  ephKeyPair: IEphemeralKeyPair;
-  bIn: TBytesStream;
-  encLength: Int32;
-  z: TBigInteger;
-  BigZ, VZ: TCryptoLibByteArray;
-  kdfParam: IKDFParameters;
-begin
-  if (FforEncryption) then
-  begin
-    if (FkeyPairGenerator <> Nil) then
-    begin
-      ephKeyPair := FkeyPairGenerator.Generate;
-
-      FprivParam := ephKeyPair.GetKeyPair.Private;
-      FV := ephKeyPair.GetEncodedPublicKey;
-    end
-  end
-  else
-  begin
-    if (FkeyParser <> Nil) then
-    begin
-      // used TBytesStream here for one pass creation and population with byte array :)
-      bIn := TBytesStream.Create(System.Copy(&in, inOff, inLen));
-
-      try
-        bIn.Position := 0;
-
-        try
-          FpubParam := FkeyParser.ReadKey(bIn);
-        except
-          on e: EIOCryptoLibException do
-          begin
-            raise EInvalidCipherTextCryptoLibException.CreateResFmt
-              (@SErrorRecoveringEphemeralPublicKey, [e.Message]);
-          end;
-
-          on e: EArgumentCryptoLibException do
-          begin
-            raise EInvalidCipherTextCryptoLibException.CreateResFmt
-              (@SErrorRecoveringEphemeralPublicKey, [e.Message]);
-          end;
-
-        end;
-
-        encLength := (inLen - (bIn.Size - bIn.Position));
-        FV := TArrayUtilities.CopyOfRange<Byte>(&in, inOff, inOff + encLength);
-
-      finally
-        bIn.Free;
-      end;
-    end;
-  end;
-
-  // Compute the common value and convert to byte array.
-  Fagree.Init(FprivParam);
-  z := Fagree.CalculateAgreement(FpubParam);
-  BigZ := TBigIntegers.AsUnsignedByteArray(Fagree.GetFieldSize, z);
-
-  // Create input to KDF.
-  if (System.Length(FV) <> 0) then
-  begin
-    VZ := TArrayUtilities.Concatenate<Byte>(FV, BigZ);
-    TArrayUtilities.Fill<Byte>(BigZ, 0, System.Length(BigZ), Byte(0));
-    BigZ := VZ;
-  end;
-
-  try
-    // Initialise the KDF.
-    kdfParam := TKDFParameters.Create(BigZ, Fparam.GetDerivationV);
-    Fkdf.Init(kdfParam);
-
-    if FforEncryption then
-    begin
-      Result := EncryptBlock(&in, inOff, inLen);
-      Exit;
-    end
-    else
-    begin
-      Result := DecryptBlock(&in, inOff, inLen);
-      Exit;
-    end;
-
-  finally
-    TArrayUtilities.Fill<Byte>(BigZ, 0, System.Length(BigZ), Byte(0));
-  end;
-end;
-
-end.

+ 645 - 0
CryptoLib/src/Crypto/Engines/ClpIesEngine.pas

@@ -0,0 +1,645 @@
+{ *********************************************************************************** }
+{ *                              CryptoLib Library                                  * }
+{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
+{ *                 Github Repository <https://github.com/Xor-el>                   * }
+
+{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
+{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
+
+{ *                              Acknowledgements:                                  * }
+{ *                                                                                 * }
+{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
+{ *                           development of this library                           * }
+
+{ * ******************************************************************************* * }
+
+(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
+
+unit ClpIesEngine;
+
+{$I ..\..\Include\CryptoLib.inc}
+
+interface
+
+uses
+  Classes,
+  SysUtils,
+  ClpIMac,
+  ClpIIesEngine,
+  ClpIBasicAgreement,
+  ClpIDerivationFunction,
+  ClpIBufferedBlockCipher,
+  ClpICipherParameters,
+  ClpIIESParameters,
+  ClpIEphemeralKeyPairGenerator,
+  ClpIAsymmetricKeyParameter,
+  ClpKeyParameter,
+  ClpIKeyParameter,
+  ClpParametersWithIV,
+  ClpIParametersWithIV,
+  ClpIKeyParser,
+  ClpIEphemeralKeyPair,
+  ClpKdfParameters,
+  ClpIKdfParameters,
+  ClpIIesWithCipherParameters,
+  ClpConverters,
+  ClpArrayUtilities,
+  ClpBigInteger,
+  ClpBigIntegers,
+  ClpCryptoLibTypes;
+
+resourcestring
+  SErrorRecoveringEphemeralPublicKey =
+    'Unable to Recover Ephemeral Public Key: "%s"';
+  SInvalidCipherTextLength =
+    'Length of Input Must be Greater than the MAC and V Combined';
+  SInvalidMAC = 'Invalid MAC';
+
+type
+
+  /// <summary>
+  /// Support class for constructing integrated encryption ciphers for doing
+  /// basic message exchanges on top of key agreement ciphers. <br />Follows
+  /// the description given in IEEE Std 1363a.
+  /// </summary>
+  TIesEngine = class(TInterfacedObject, IIesEngine)
+
+  strict private
+  var
+    FParam: IIesParameters;
+
+    // as described in Shroup's paper( ch 10, pg 20) and P1363a
+    function GetLengthTag(const AP2: TCryptoLibByteArray)
+      : TCryptoLibByteArray; inline;
+
+    procedure ExtractParams(const AParams: ICipherParameters); inline;
+
+    function SimilarMacCompute(const AArgOne, AArgTwo: TCryptoLibByteArray)
+      : TCryptoLibByteArray; inline;
+
+  strict protected
+
+  var
+    FAgree: IBasicAgreement;
+    FKdf: IDerivationFunction;
+    FMac: IMac;
+    FCipher: IBufferedBlockCipher;
+    FV, FIV: TCryptoLibByteArray;
+    FForEncryption: Boolean;
+    FPrivParam, FPubParam: ICipherParameters;
+    FKeyPairGenerator: IEphemeralKeyPairGenerator;
+    FKeyParser: IKeyParser;
+
+    function GetCipher: IBufferedBlockCipher; inline;
+    function GetMac: IMac; inline;
+    procedure SetupBlockCipherAndMacKeyBytes(out AK1,
+      AK2: TCryptoLibByteArray); inline;
+
+    function EncryptBlock(const AIn: TCryptoLibByteArray; AInOff, AInLen: Int32)
+      : TCryptoLibByteArray; virtual;
+
+    function DecryptBlock(const AInEnc: TCryptoLibByteArray;
+      AInOff, AInLen: Int32): TCryptoLibByteArray; virtual;
+
+  public
+
+    /// <summary>
+    /// Set up for use with stream mode, where the key derivation function is
+    /// used to provide a stream of bytes to xor with the message.
+    /// </summary>
+    /// <param name="AAgree">
+    /// the key agreement used as the basis for the encryption
+    /// </param>
+    /// <param name="AKdf">
+    /// the key derivation function used for byte generation
+    /// </param>
+    /// <param name="AMac">
+    /// the message authentication code generator for the message
+    /// </param>
+    constructor Create(const AAgree: IBasicAgreement;
+      const AKdf: IDerivationFunction; const AMac: IMac); overload;
+
+    /// <summary>
+    /// Set up for use in conjunction with a block cipher to handle the <br />
+    /// message. It is <b>strongly</b> recommended that the cipher is not
+    /// in ECB mode.
+    /// </summary>
+    /// <param name="AAgree">
+    /// the key agreement used as the basis for the encryption
+    /// </param>
+    /// <param name="AKdf">
+    /// the key derivation function used for byte generation
+    /// </param>
+    /// <param name="AMac">
+    /// the message authentication code generator for the message
+    /// </param>
+    /// <param name="ACipher">
+    /// the cipher to used for encrypting the message
+    /// </param>
+    constructor Create(const AAgree: IBasicAgreement;
+      const AKdf: IDerivationFunction; const AMac: IMac;
+      const ACipher: IBufferedBlockCipher); overload;
+
+    /// <summary>
+    /// Initialise the encryptor/decryptor.
+    /// </summary>
+    /// <param name="forEncryption">
+    /// whether or not this is encryption/decryption.
+    /// </param>
+    /// <param name="APrivParam">
+    /// our private key parameters
+    /// </param>
+    /// <param name="APubParam">
+    /// the recipient's/sender's public key parameters
+    /// </param>
+    /// <param name="AParams">
+    /// encoding and derivation parameters, may be wrapped to include an IV
+    /// for an underlying block cipher.
+    /// </param>
+    procedure Init(AForEncryption: Boolean; const APrivParam, APubParam,
+      AParams: ICipherParameters); overload;
+
+    /// <summary>
+    /// Initialise the encryptor.
+    /// </summary>
+    /// <param name="APublicKey">
+    /// the recipient's/sender's public key parameters
+    /// </param>
+    /// <param name="AParams">
+    /// encoding and derivation parameters, may be wrapped to include an IV
+    /// for an underlying block cipher.
+    /// </param>
+    /// <param name="AEphemeralKeyPairGenerator">
+    /// the ephemeral key pair generator to use.
+    /// </param>
+    procedure Init(const APublicKey: IAsymmetricKeyParameter;
+      const AParams: ICipherParameters;
+      const AEphemeralKeyPairGenerator: IEphemeralKeyPairGenerator); overload;
+
+    /// <summary>
+    /// Initialise the decryptor.
+    /// </summary>
+    /// <param name="APrivateKey">
+    /// the recipient's private key.
+    /// </param>
+    /// <param name="AParams">
+    /// encoding and derivation parameters, may be wrapped to include an IV
+    /// for an underlying block cipher.
+    /// </param>
+    /// <param name="APublicKeyParser">
+    /// the parser for reading the ephemeral public key.
+    /// </param>
+    procedure Init(const APrivateKey: IAsymmetricKeyParameter;
+      const AParams: ICipherParameters;
+      const APublicKeyParser: IKeyParser); overload;
+
+    function ProcessBlock(const AIn: TCryptoLibByteArray; AInOff, AInLen: Int32)
+      : TCryptoLibByteArray; virtual;
+
+    property Cipher: IBufferedBlockCipher read GetCipher;
+    property Mac: IMac read GetMac;
+
+  end;
+
+implementation
+
+{ TIESEngine }
+
+function TIesEngine.GetLengthTag(const AP2: TCryptoLibByteArray)
+  : TCryptoLibByteArray;
+begin
+  System.SetLength(Result, 8);
+  if (AP2 <> nil) then
+  begin
+    TConverters.ReadUInt64AsBytesBE(System.Length(AP2) * 8, Result, 0);
+  end;
+end;
+
+function TIesEngine.SimilarMacCompute(const AArgOne, AArgTwo: TCryptoLibByteArray)
+  : TCryptoLibByteArray;
+begin
+  if (AArgOne <> nil) then
+  begin
+    FMac.BlockUpdate(AArgOne, 0, System.Length(AArgOne));
+  end;
+  if (System.Length(FV) <> 0) then
+  begin
+    FMac.BlockUpdate(AArgTwo, 0, System.Length(AArgTwo));
+  end;
+  Result := FMac.DoFinal;
+end;
+
+procedure TIesEngine.SetupBlockCipherAndMacKeyBytes(out AK1,
+  AK2: TCryptoLibByteArray);
+var
+  LK: TCryptoLibByteArray;
+  LWithCipher: IIesWithCipherParameters;
+begin
+  if not Supports(FParam, IIesWithCipherParameters, LWithCipher) then
+    raise EArgumentCryptoLibException.Create('IES parameters must support IIesWithCipherParameters for block cipher mode');
+  System.SetLength(AK1, LWithCipher.CipherKeySize div 8);
+  System.SetLength(AK2, FParam.MacKeySize div 8);
+  System.SetLength(LK, System.Length(AK1) + System.Length(AK2));
+
+  FKdf.GenerateBytes(LK, 0, System.Length(LK));
+
+  System.Move(LK[0], AK1[0], System.Length(AK1) * System.SizeOf(Byte));
+  System.Move(LK[System.Length(AK1)], AK2[0], System.Length(AK2) *
+    System.SizeOf(Byte));
+end;
+
+constructor TIesEngine.Create(const AAgree: IBasicAgreement;
+  const AKdf: IDerivationFunction; const AMac: IMac);
+begin
+  Inherited Create();
+  FAgree := AAgree;
+  FKdf := AKdf;
+  FMac := AMac;
+  FCipher := nil;
+end;
+
+constructor TIesEngine.Create(const AAgree: IBasicAgreement;
+  const AKdf: IDerivationFunction; const AMac: IMac;
+  const ACipher: IBufferedBlockCipher);
+begin
+  Inherited Create();
+  FAgree := AAgree;
+  FKdf := AKdf;
+  FMac := AMac;
+  FCipher := ACipher;
+end;
+
+function TIesEngine.DecryptBlock(const AInEnc: TCryptoLibByteArray;
+  AInOff, AInLen: Int32): TCryptoLibByteArray;
+var
+  LM, LK, LK1, LK2, LP2, LL2, LT1, LT2: TCryptoLibByteArray;
+  LLen, LI, LEndPoint: Int32;
+  LCp: ICipherParameters;
+begin
+  LLen := 0;
+  // Ensure that the length of the input is greater than the MAC in bytes
+  if (AInLen < (System.Length(FV) + FMac.GetMacSize)) then
+  begin
+    raise EInvalidCipherTextCryptoLibException.CreateRes
+      (@SInvalidCipherTextLength);
+  end;
+  // note order is important: set up keys, do simple encryptions, check mac, do final encryption.
+  if (FCipher = nil) then
+  begin
+
+    // Streaming mode.
+    System.SetLength(LK1, AInLen - System.Length(FV) - FMac.GetMacSize);
+    System.SetLength(LK2, FParam.MacKeySize div 8);
+    System.SetLength(LK, System.Length(LK1) + System.Length(LK2));
+
+    FKdf.GenerateBytes(LK, 0, System.Length(LK));
+
+    if (System.Length(FV) <> 0) then
+    begin
+      System.Move(LK[0], LK2[0], System.Length(LK2) * System.SizeOf(Byte));
+      if LK1 <> nil then
+      begin
+        System.Move(LK[System.Length(LK2)], LK1[0],
+          System.Length(LK1) * System.SizeOf(Byte));
+      end;
+    end
+    else
+    begin
+      if LK1 <> nil then
+      begin
+        System.Move(LK[0], LK1[0], System.Length(LK1) * System.SizeOf(Byte));
+      end;
+      System.Move(LK[System.Length(LK1)], LK2[0], System.Length(LK2) *
+        System.SizeOf(Byte));
+    end;
+
+    // process the message
+    System.SetLength(LM, System.Length(LK1));
+
+    LI := 0;
+
+    while LI <> System.Length(LK1) do
+    begin
+      LM[LI] := Byte(AInEnc[AInOff + System.Length(FV) + LI] xor LK1[LI]);
+      System.Inc(LI);
+    end;
+
+  end
+  else
+  begin
+    // Block cipher mode.
+
+    SetupBlockCipherAndMacKeyBytes(LK1, LK2);
+
+    LCp := TKeyParameter.Create(LK1);
+
+    // If iv is provided use it to initialise the cipher
+    if (FIV <> nil) then
+    begin
+      LCp := TParametersWithIV.Create(LCp, FIV);
+    end;
+
+    FCipher.Init(False, LCp);
+
+    System.SetLength(LM, FCipher.GetOutputSize(AInLen - System.Length(FV) -
+      FMac.GetMacSize));
+
+    // do initial processing
+    LLen := FCipher.ProcessBytes(AInEnc, AInOff + System.Length(FV),
+      AInLen - System.Length(FV) - FMac.GetMacSize, LM, 0);
+
+  end;
+
+  // Convert the length of the encoding vector into a byte array.
+  LP2 := FParam.GetEncodingV();
+  LL2 := nil;
+  if (System.Length(FV) <> 0) then
+  begin
+    LL2 := GetLengthTag(LP2);
+  end;
+
+  // Verify the MAC.
+  LEndPoint := AInOff + AInLen;
+  LT1 := TArrayUtilities.CopyOfRange<Byte>(AInEnc, LEndPoint - FMac.GetMacSize, LEndPoint);
+  System.SetLength(LT2, System.Length(LT1));
+
+  FMac.Init((TKeyParameter.Create(LK2) as IKeyParameter) as ICipherParameters);
+
+  FMac.BlockUpdate(AInEnc, AInOff + System.Length(FV), AInLen - System.Length(FV)
+    - System.Length(LT2));
+
+  LT2 := SimilarMacCompute(LP2, LL2);
+
+  if not TArrayUtilities.FixedTimeEquals(LT1, LT2) then
+  begin
+    raise EInvalidCipherTextCryptoLibException.CreateRes(@SInvalidMAC);
+  end;
+
+  if (FCipher = nil) then
+  begin
+    Result := LM;
+    Exit;
+  end
+  else
+  begin
+    LLen := LLen + FCipher.DoFinal(LM, LLen);
+
+    Result := TArrayUtilities.CopyOfRange<Byte>(LM, 0, LLen);
+    Exit;
+  end;
+end;
+
+function TIesEngine.EncryptBlock(const AIn: TCryptoLibByteArray;
+  AInOff, AInLen: Int32): TCryptoLibByteArray;
+var
+  LC, LK, LK1, LK2, LP2, LL2, LT: TCryptoLibByteArray;
+  LLen, LI, LLenCount: Int32;
+begin
+  if (FCipher = nil) then
+  begin
+    // Streaming mode.
+    System.SetLength(LK1, AInLen);
+    System.SetLength(LK2, FParam.MacKeySize div 8);
+    System.SetLength(LK, System.Length(LK1) + System.Length(LK2));
+
+    FKdf.GenerateBytes(LK, 0, System.Length(LK));
+
+    if (System.Length(FV) <> 0) then
+    begin
+      System.Move(LK[0], LK2[0], System.Length(LK2) * System.SizeOf(Byte));
+      if LK1 <> nil then
+      begin
+        System.Move(LK[System.Length(LK2)], LK1[0],
+          System.Length(LK1) * System.SizeOf(Byte));
+      end;
+    end
+    else
+    begin
+      if LK1 <> nil then
+      begin
+        System.Move(LK[0], LK1[0], System.Length(LK1) * System.SizeOf(Byte));
+      end;
+      System.Move(LK[AInLen], LK2[0], System.Length(LK2) * System.SizeOf(Byte));
+    end;
+
+    System.SetLength(LC, AInLen);
+
+    LI := 0;
+
+    while LI <> AInLen do
+    begin
+      LC[LI] := Byte(AIn[AInOff + LI] xor LK1[LI]);
+      System.Inc(LI);
+    end;
+
+    LLen := AInLen;
+  end
+  else
+  begin
+    // Block cipher mode.
+
+    SetupBlockCipherAndMacKeyBytes(LK1, LK2);
+
+    // If iv is provided use it to initialise the cipher
+    if (FIV <> nil) then
+    begin
+      FCipher.Init(True, TParametersWithIV.Create(TKeyParameter.Create(LK1)
+        as IKeyParameter, FIV) as IParametersWithIV);
+    end
+    else
+    begin
+      FCipher.Init(True, TKeyParameter.Create(LK1) as IKeyParameter);
+    end;
+
+    System.SetLength(LC, FCipher.GetOutputSize(AInLen));
+
+    LLen := FCipher.ProcessBytes(AIn, AInOff, AInLen, LC, 0);
+    LLen := LLen + FCipher.DoFinal(LC, LLen);
+  end;
+
+  // Convert the length of the encoding vector into a byte array.
+  LP2 := FParam.GetEncodingV();
+  LL2 := nil;
+  if (System.Length(FV) <> 0) then
+  begin
+    LL2 := GetLengthTag(LP2);
+  end;
+
+  // Apply the MAC.
+  System.SetLength(LT, FMac.GetMacSize);
+
+  FMac.Init((TKeyParameter.Create(LK2) as IKeyParameter) as ICipherParameters);
+  FMac.BlockUpdate(LC, 0, System.Length(LC));
+
+  LT := SimilarMacCompute(LP2, LL2);
+
+  // Output the triple (V,C,T).
+  // V := Ephermeral Public Key
+  // C := Encrypted Payload
+  // T := Authentication Message (MAC)
+  System.SetLength(Result, System.Length(FV) + LLen + System.Length(LT));
+  if FV <> nil then
+  begin
+    System.Move(FV[0], Result[0], System.Length(FV) * System.SizeOf(Byte));
+  end;
+  LLenCount := LLen * System.SizeOf(Byte);
+  if LLenCount > 0 then
+  begin
+    System.Move(LC[0], Result[System.Length(FV)], LLenCount);
+  end;
+  System.Move(LT[0], Result[System.Length(FV) + LLen],
+    System.Length(LT) * System.SizeOf(Byte));
+
+end;
+
+procedure TIesEngine.ExtractParams(const AParams: ICipherParameters);
+var
+  LParamsWithIV: IParametersWithIV;
+  LIesParams: IIesParameters;
+begin
+  if Supports(AParams, IParametersWithIV, LParamsWithIV) then
+  begin
+    FIV := LParamsWithIV.GetIV;
+    if not Supports(LParamsWithIV.Parameters, IIesParameters, LIesParams) then
+      raise EArgumentCryptoLibException.Create('Parameters must support IIesParameters');
+    FParam := LIesParams;
+  end
+  else
+  begin
+    FIV := nil;
+    if not Supports(AParams, IIesParameters, LIesParams) then
+      raise EArgumentCryptoLibException.Create('Parameters must support IIesParameters');
+    FParam := LIesParams;
+  end;
+end;
+
+function TIesEngine.GetCipher: IBufferedBlockCipher;
+begin
+  Result := FCipher;
+end;
+
+function TIesEngine.GetMac: IMac;
+begin
+  Result := FMac;
+end;
+
+procedure TIesEngine.Init(const APrivateKey: IAsymmetricKeyParameter;
+  const AParams: ICipherParameters; const APublicKeyParser: IKeyParser);
+begin
+  FForEncryption := False;
+  FPrivParam := APrivateKey;
+  FKeyParser := APublicKeyParser;
+  ExtractParams(AParams);
+end;
+
+procedure TIesEngine.Init(const APublicKey: IAsymmetricKeyParameter;
+  const AParams: ICipherParameters;
+  const AEphemeralKeyPairGenerator: IEphemeralKeyPairGenerator);
+begin
+  FForEncryption := True;
+  FPubParam := APublicKey;
+  FKeyPairGenerator := AEphemeralKeyPairGenerator;
+  ExtractParams(AParams);
+end;
+
+procedure TIesEngine.Init(AForEncryption: Boolean;
+  const APrivParam, APubParam, AParams: ICipherParameters);
+begin
+  FForEncryption := AForEncryption;
+  FPrivParam := APrivParam;
+  FPubParam := APubParam;
+  System.SetLength(FV, 0);
+  ExtractParams(AParams);
+end;
+
+function TIesEngine.ProcessBlock(const AIn: TCryptoLibByteArray;
+  AInOff, AInLen: Int32): TCryptoLibByteArray;
+var
+  ephKeyPair: IEphemeralKeyPair;
+  bIn: TBytesStream;
+  encLength: Int32;
+  z: TBigInteger;
+  BigZ, VZ: TCryptoLibByteArray;
+  kdfParam: IKDFParameters;
+begin
+  if (FForEncryption) then
+  begin
+    if (FKeyPairGenerator <> nil) then
+    begin
+      ephKeyPair := FKeyPairGenerator.Generate;
+
+      FPrivParam := ephKeyPair.GetKeyPair.Private;
+      FV := ephKeyPair.GetEncodedPublicKey;
+    end
+  end
+  else
+  begin
+    if (FKeyParser <> nil) then
+    begin
+      // used TBytesStream here for one pass creation and population with byte array :)
+      bIn := TBytesStream.Create(System.Copy(AIn, AInOff, AInLen));
+
+      try
+        bIn.Position := 0;
+
+        try
+          FPubParam := FKeyParser.ReadKey(bIn);
+        except
+          on e: EIOCryptoLibException do
+          begin
+            raise EInvalidCipherTextCryptoLibException.CreateResFmt
+              (@SErrorRecoveringEphemeralPublicKey, [e.Message]);
+          end;
+
+          on e: EArgumentCryptoLibException do
+          begin
+            raise EInvalidCipherTextCryptoLibException.CreateResFmt
+              (@SErrorRecoveringEphemeralPublicKey, [e.Message]);
+          end;
+
+        end;
+
+        encLength := (AInLen - (bIn.Size - bIn.Position));
+        FV := TArrayUtilities.CopyOfRange<Byte>(AIn, AInOff, AInOff + encLength);
+
+      finally
+        bIn.Free;
+      end;
+    end;
+  end;
+
+  // Compute the common value and convert to byte array.
+  FAgree.Init(FPrivParam);
+  z := FAgree.CalculateAgreement(FPubParam);
+  BigZ := TBigIntegers.AsUnsignedByteArray(FAgree.GetFieldSize, z);
+
+  // Create input to KDF.
+  if (System.Length(FV) <> 0) then
+  begin
+    VZ := TArrayUtilities.Concatenate<Byte>(FV, BigZ);
+    TArrayUtilities.Fill<Byte>(BigZ, 0, System.Length(BigZ), Byte(0));
+    BigZ := VZ;
+  end;
+
+  try
+    // Initialise the KDF.
+    kdfParam := TKDFParameters.Create(BigZ, FParam.GetDerivationV);
+    FKdf.Init(kdfParam);
+
+    if FForEncryption then
+    begin
+      Result := EncryptBlock(AIn, AInOff, AInLen);
+      Exit;
+    end
+    else
+    begin
+      Result := DecryptBlock(AIn, AInOff, AInLen);
+      Exit;
+    end;
+
+  finally
+    TArrayUtilities.Fill<Byte>(BigZ, 0, System.Length(BigZ), Byte(0));
+  end;
+end;
+
+end.

+ 85 - 85
CryptoLib/src/Crypto/Engines/ClpPascalCoinIESEngine.pas → CryptoLib/src/Crypto/Engines/ClpPascalCoinIesEngine.pas

@@ -15,7 +15,7 @@
 
 (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
 
-unit ClpPascalCoinIESEngine;
+unit ClpPascalCoinIesEngine;
 
 {$I ..\..\Include\CryptoLib.inc}
 
@@ -53,7 +53,7 @@ type
   /// <summary>
   /// Compatibility Class for PascalCoin IESEngine
   /// </summary>
-  TPascalCoinIESEngine = class(TIESEngine, IPascalCoinIESEngine)
+  TPascalCoinIesEngine = class(TIesEngine, IPascalCoinIesEngine)
 
   strict private
   type
@@ -77,15 +77,15 @@ type
 
   strict protected
 
-    function EncryptBlock(const &in: TCryptoLibByteArray; inOff, inLen: Int32)
+    function EncryptBlock(const AIn: TCryptoLibByteArray; AInOff, AInLen: Int32)
       : TCryptoLibByteArray; override;
 
-    function DecryptBlock(const in_enc: TCryptoLibByteArray;
-      inOff, inLen: Int32): TCryptoLibByteArray; override;
+    function DecryptBlock(const AInEnc: TCryptoLibByteArray;
+      AInOff, AInLen: Int32): TCryptoLibByteArray; override;
 
   public
 
-    function ProcessBlock(const &in: TCryptoLibByteArray; inOff, inLen: Int32)
+    function ProcessBlock(const AIn: TCryptoLibByteArray; AInOff, AInLen: Int32)
       : TCryptoLibByteArray; override;
 
   end;
@@ -94,20 +94,20 @@ implementation
 
 { TPascalCoinIESEngine }
 
-function TPascalCoinIESEngine.DecryptBlock(const in_enc: TCryptoLibByteArray;
-  inOff, inLen: Int32): TCryptoLibByteArray;
+function TPascalCoinIesEngine.DecryptBlock(const AInEnc: TCryptoLibByteArray;
+  AInOff, AInLen: Int32): TCryptoLibByteArray;
 var
-  K1, K2, T1, T2: TCryptoLibByteArray;
-  cp: ICipherParameters;
+  LK1, LK2, LT1, LT2: TCryptoLibByteArray;
+  LCp: ICipherParameters;
 begin
   // Ensure that the length of the input is greater than the MAC in bytes
-  if (inLen < (System.Length(FV) + Fmac.GetMacSize)) then
+  if (AInLen < (System.Length(FV) + FMac.GetMacSize)) then
   begin
     raise EInvalidCipherTextCryptoLibException.CreateRes
       (@SInvalidCipherTextLength);
   end;
   // note order is important: set up keys, do simple encryptions, check mac, do final encryption.
-  if (Fcipher = Nil) then
+  if (FCipher = nil) then
   begin
     raise EArgumentNilCryptoLibException.CreateRes
       (@SCipherCannotbeNilInThisMode);
@@ -116,48 +116,48 @@ begin
   begin
     // Block cipher mode.
 
-    SetupBlockCipherAndMacKeyBytes(K1, K2);
+    SetupBlockCipherAndMacKeyBytes(LK1, LK2);
 
-    cp := TKeyParameter.Create(K1);
+    LCp := TKeyParameter.Create(LK1);
 
     // If iv is provided use it to initialise the cipher
-    if (FIV <> Nil) then
+    if (FIV <> nil) then
     begin
-      cp := TParametersWithIV.Create(cp, FIV);
+      LCp := TParametersWithIV.Create(LCp, FIV);
     end;
 
-    Fcipher.Init(False, cp);
+    FCipher.Init(False, LCp);
 
   end;
 
   // Verify the MAC.
-  T1 := System.Copy(in_enc, System.Length(FV), Fmac.GetMacSize);
-  System.SetLength(T2, System.Length(T1));
+  LT1 := System.Copy(AInEnc, System.Length(FV), FMac.GetMacSize);
+  System.SetLength(LT2, System.Length(LT1));
 
-  Fmac.Init((TKeyParameter.Create(K2) as IKeyParameter) as ICipherParameters);
+  FMac.Init((TKeyParameter.Create(LK2) as IKeyParameter) as ICipherParameters);
 
-  Fmac.BlockUpdate(in_enc, inOff + System.Length(FV) + System.Length(T2),
-    inLen - System.Length(FV) - System.Length(T2));
+  FMac.BlockUpdate(AInEnc, AInOff + System.Length(FV) + System.Length(LT2),
+    AInLen - System.Length(FV) - System.Length(LT2));
 
-  T2 := Fmac.DoFinal();
+  LT2 := FMac.DoFinal();
 
-  if not TArrayUtilities.FixedTimeEquals(T1, T2) then
+  if not TArrayUtilities.FixedTimeEquals(LT1, LT2) then
   begin
     raise EInvalidCipherTextCryptoLibException.CreateRes(@SInvalidMAC);
   end;
 
-  Result := Fcipher.DoFinal(in_enc, inOff + System.Length(FV) + Fmac.GetMacSize,
-    inLen - System.Length(FV) - System.Length(T2));
+  Result := FCipher.DoFinal(AInEnc, AInOff + System.Length(FV) + FMac.GetMacSize,
+    AInLen - System.Length(FV) - System.Length(LT2));
   Exit;
 end;
 
-function TPascalCoinIESEngine.EncryptBlock(const &in: TCryptoLibByteArray;
-  inOff, inLen: Int32): TCryptoLibByteArray;
+function TPascalCoinIesEngine.EncryptBlock(const AIn: TCryptoLibByteArray;
+  AInOff, AInLen: Int32): TCryptoLibByteArray;
 var
-  C, K1, K2, T: TCryptoLibByteArray;
-  MessageToEncryptPadSize, CipherBlockSize, MessageToEncryptSize: Int32;
+  LC, LK1, LK2, LT: TCryptoLibByteArray;
+  LMessageToEncryptPadSize, LCipherBlockSize, LMessageToEncryptSize: Int32;
 begin
-  if (Fcipher = Nil) then
+  if (FCipher = nil) then
   begin
     raise EArgumentNilCryptoLibException.CreateRes
       (@SCipherCannotbeNilInThisMode);
@@ -166,41 +166,41 @@ begin
   begin
     // Block cipher mode.
 
-    SetupBlockCipherAndMacKeyBytes(K1, K2);
+    SetupBlockCipherAndMacKeyBytes(LK1, LK2);
 
     // If iv is provided use it to initialise the cipher
-    if (FIV <> Nil) then
+    if (FIV <> nil) then
     begin
-      Fcipher.Init(true, TParametersWithIV.Create(TKeyParameter.Create(K1)
+      FCipher.Init(True, TParametersWithIV.Create(TKeyParameter.Create(LK1)
         as IKeyParameter, FIV));
     end
     else
     begin
-      Fcipher.Init(true, TKeyParameter.Create(K1) as IKeyParameter);
+      FCipher.Init(True, TKeyParameter.Create(LK1) as IKeyParameter);
     end;
 
-    C := Fcipher.DoFinal(&in, inOff, inLen);
+    LC := FCipher.DoFinal(AIn, AInOff, AInLen);
   end;
 
   // Apply the MAC.
-  System.SetLength(T, Fmac.GetMacSize);
+  System.SetLength(LT, FMac.GetMacSize);
 
-  Fmac.Init((TKeyParameter.Create(K2) as IKeyParameter) as ICipherParameters);
+  FMac.Init((TKeyParameter.Create(LK2) as IKeyParameter) as ICipherParameters);
 
-  Fmac.BlockUpdate(C, 0, System.Length(C));
+  FMac.BlockUpdate(LC, 0, System.Length(LC));
 
-  T := Fmac.DoFinal();
-  CipherBlockSize := Fcipher.GetBlockSize;
-  MessageToEncryptSize := inLen - inOff;
+  LT := FMac.DoFinal();
+  LCipherBlockSize := FCipher.GetBlockSize;
+  LMessageToEncryptSize := AInLen - AInOff;
 
-  if (MessageToEncryptSize mod CipherBlockSize) = 0 then
+  if (LMessageToEncryptSize mod LCipherBlockSize) = 0 then
   begin
-    MessageToEncryptPadSize := 0
+    LMessageToEncryptPadSize := 0
   end
   else
   begin
-    MessageToEncryptPadSize := CipherBlockSize -
-      (MessageToEncryptSize mod CipherBlockSize);
+    LMessageToEncryptPadSize := LCipherBlockSize -
+      (LMessageToEncryptSize mod LCipherBlockSize);
   end;
   // Output the quadruple (SECURE_HEAD_DETAILS,V,T,C).
   // SECURE_HEAD_DETAILS :=
@@ -213,58 +213,58 @@ begin
   // C := Encrypted Payload
 
   System.SetLength(Result, SECURE_HEAD_SIZE + System.Length(FV) +
-    System.Length(T) + System.Length(C));
+    System.Length(LT) + System.Length(LC));
 
   PByte(Result)^ := Byte(System.Length(FV));
-  (PByte(Result) + 1)^ := Byte(System.Length(T));
-  (PWord(Result) + 1)^ := UInt16(MessageToEncryptSize);
+  (PByte(Result) + 1)^ := Byte(System.Length(LT));
+  (PWord(Result) + 1)^ := UInt16(LMessageToEncryptSize);
   (PWord(Result) + 2)^ :=
-    UInt16(MessageToEncryptSize + MessageToEncryptPadSize);
+    UInt16(LMessageToEncryptSize + LMessageToEncryptPadSize);
 
   System.Move(FV[0], Result[SECURE_HEAD_SIZE], System.Length(FV) *
     System.SizeOf(Byte));
 
-  System.Move(T[0], Result[SECURE_HEAD_SIZE + System.Length(FV)],
-    System.Length(T) * System.SizeOf(Byte));
+  System.Move(LT[0], Result[SECURE_HEAD_SIZE + System.Length(FV)],
+    System.Length(LT) * System.SizeOf(Byte));
 
-  System.Move(C[0], Result[SECURE_HEAD_SIZE + System.Length(FV) +
-    System.Length(T)], System.Length(C) * System.SizeOf(Byte));
+  System.Move(LC[0], Result[SECURE_HEAD_SIZE + System.Length(FV) +
+    System.Length(LT)], System.Length(LC) * System.SizeOf(Byte));
 
 end;
 
-function TPascalCoinIESEngine.ProcessBlock(const &in: TCryptoLibByteArray;
-  inOff, inLen: Int32): TCryptoLibByteArray;
+function TPascalCoinIesEngine.ProcessBlock(const AIn: TCryptoLibByteArray;
+  AInOff, AInLen: Int32): TCryptoLibByteArray;
 var
-  ephKeyPair: IEphemeralKeyPair;
-  bIn: TBytesStream;
-  encLength: Int32;
-  z: TBigInteger;
-  BigZ: TCryptoLibByteArray;
-  kdfParam: IKDFParameters;
+  LEphKeyPair: IEphemeralKeyPair;
+  LBIn: TBytesStream;
+  LEncLength: Int32;
+  LZ: TBigInteger;
+  LBigZ: TCryptoLibByteArray;
+  LKdfParam: IKDFParameters;
 begin
-  if (FforEncryption) then
+  if (FForEncryption) then
   begin
-    if (FkeyPairGenerator <> Nil) then
+    if (FKeyPairGenerator <> nil) then
     begin
-      ephKeyPair := FkeyPairGenerator.Generate;
+      LEphKeyPair := FKeyPairGenerator.Generate;
 
-      FprivParam := ephKeyPair.GetKeyPair.Private;
-      FV := ephKeyPair.GetEncodedPublicKey;
+      FPrivParam := LEphKeyPair.GetKeyPair.Private;
+      FV := LEphKeyPair.GetEncodedPublicKey;
     end
   end
   else
   begin
-    if (FkeyParser <> Nil) then
+    if (FKeyParser <> nil) then
     begin
       // used TBytesStream here for one pass creation and population with byte array :)
-      bIn := TBytesStream.Create(System.Copy(&in, inOff, inLen));
+      LBIn := TBytesStream.Create(System.Copy(AIn, AInOff, AInLen));
 
       try
         // for existing PascalCoin compatiblity purposes
-        bIn.Position := SECURE_HEAD_SIZE;
+        LBIn.Position := SECURE_HEAD_SIZE;
 
         try
-          FpubParam := FkeyParser.ReadKey(bIn);
+          FPubParam := FKeyParser.ReadKey(LBIn);
         except
           on e: EIOCryptoLibException do
           begin
@@ -280,40 +280,40 @@ begin
 
         end;
 
-        encLength := (inLen - (bIn.Size - bIn.Position));
-        FV := TArrayUtilities.CopyOfRange<Byte>(&in, inOff + SECURE_HEAD_SIZE,
-          inOff + encLength);
+        LEncLength := (AInLen - (LBIn.Size - LBIn.Position));
+        FV := TArrayUtilities.CopyOfRange<Byte>(AIn, AInOff + SECURE_HEAD_SIZE,
+          AInOff + LEncLength);
 
       finally
-        bIn.Free;
+        LBIn.Free;
       end;
     end;
   end;
 
   // Compute the common value and convert to byte array.
-  Fagree.Init(FprivParam);
-  z := Fagree.CalculateAgreement(FpubParam);
-  BigZ := TBigIntegers.AsUnsignedByteArray(Fagree.GetFieldSize, z);
+  FAgree.Init(FPrivParam);
+  LZ := FAgree.CalculateAgreement(FPubParam);
+  LBigZ := TBigIntegers.AsUnsignedByteArray(FAgree.GetFieldSize, LZ);
 
   try
     // Initialise the KDF.
-    kdfParam := TKDFParameters.Create(BigZ, Nil);
-    Fkdf.Init(kdfParam);
+    LKdfParam := TKDFParameters.Create(LBigZ, nil);
+    FKdf.Init(LKdfParam);
 
-    if FforEncryption then
+    if FForEncryption then
     begin
-      Result := EncryptBlock(&in, inOff, inLen);
+      Result := EncryptBlock(AIn, AInOff, AInLen);
       Exit;
     end
     else
     begin
-      Result := DecryptBlock(System.Copy(&in, inOff + SECURE_HEAD_SIZE,
-        inLen - SECURE_HEAD_SIZE), inOff, inLen - SECURE_HEAD_SIZE);
+      Result := DecryptBlock(System.Copy(AIn, AInOff + SECURE_HEAD_SIZE,
+        AInLen - SECURE_HEAD_SIZE), AInOff, AInLen - SECURE_HEAD_SIZE);
       Exit;
     end;
 
   finally
-    TArrayUtilities.Fill<Byte>(BigZ, 0, System.Length(BigZ), Byte(0));
+    TArrayUtilities.Fill<Byte>(LBigZ, 0, System.Length(LBigZ), Byte(0));
   end;
 end;
 

+ 81 - 0
CryptoLib/src/Crypto/Parameters/ClpIesCipherParameters.pas

@@ -0,0 +1,81 @@
+{ *********************************************************************************** }
+{ *                              CryptoLib Library                                  * }
+{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
+{ *                 Github Repository <https://github.com/Xor-el>                   * }
+
+{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
+{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
+
+{ *                              Acknowledgements:                                  * }
+{ *                                                                                 * }
+{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
+{ *                           development of this library                           * }
+
+{ * ******************************************************************************* * }
+
+(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
+
+unit ClpIesCipherParameters;
+
+{$I ..\..\Include\CryptoLib.inc}
+
+interface
+
+uses
+  ClpICipherParameters,
+  ClpIIESParameters,
+  ClpIIesCipherParameters,
+  ClpCryptoLibTypes;
+
+type
+  TIesCipherParameters = class sealed(TInterfacedObject, IIesCipherParameters,
+    ICipherParameters)
+
+  strict private
+  var
+    FPrivateKey: ICipherParameters;
+    FPublicKey: ICipherParameters;
+    FIesParameters: IIesParameters;
+
+    function GetPrivateKey: ICipherParameters; inline;
+    function GetPublicKey: ICipherParameters; inline;
+    function GetIesParameters: IIesParameters; inline;
+
+  public
+    constructor Create(const APrivateKey, APublicKey: ICipherParameters;
+      const AIesParameters: IIesParameters);
+
+    property PrivateKey: ICipherParameters read GetPrivateKey;
+    property PublicKey: ICipherParameters read GetPublicKey;
+    property IesParameters: IIesParameters read GetIesParameters;
+  end;
+
+implementation
+
+{ TIesCipherParameters }
+
+constructor TIesCipherParameters.Create(const APrivateKey,
+  APublicKey: ICipherParameters; const AIesParameters: IIesParameters);
+begin
+  Inherited Create();
+  FPrivateKey := APrivateKey;
+  FPublicKey := APublicKey;
+  FIesParameters := AIesParameters;
+end;
+
+function TIesCipherParameters.GetPrivateKey: ICipherParameters;
+begin
+  Result := FPrivateKey;
+end;
+
+function TIesCipherParameters.GetPublicKey: ICipherParameters;
+begin
+  Result := FPublicKey;
+end;
+
+function TIesCipherParameters.GetIesParameters: IIesParameters;
+begin
+  Result := FIesParameters;
+end;
+
+end.

+ 17 - 17
CryptoLib/src/Crypto/Parameters/ClpIESParameters.pas → CryptoLib/src/Crypto/Parameters/ClpIesParameters.pas

@@ -31,7 +31,7 @@ type
   /// <summary>
   /// parameters for using an integrated cipher in stream mode.
   /// </summary>
-  TIESParameters = class(TInterfacedObject, IIESParameters, ICipherParameters)
+  TIesParameters = class(TInterfacedObject, IIesParameters, ICipherParameters)
 
   strict private
   var
@@ -44,45 +44,45 @@ type
     function GetEncodingV(): TCryptoLibByteArray; inline;
     property MacKeySize: Int32 read GetMacKeySize;
 
-    /// <param name="derivation">
+    /// <param name="ADerivation">
     /// the derivation parameter for the KDF function.
     /// </param>
-    /// <param name="encoding">
+    /// <param name="AEncoding">
     /// the encoding parameter for the KDF function.
     /// </param>
-    /// <param name="MacKeySize">
+    /// <param name="AMacKeySize">
     /// the size of the MAC key (in bits).
     /// </param>
-    constructor Create(const derivation, encoding: TCryptoLibByteArray;
-      MacKeySize: Int32);
+    constructor Create(const ADerivation, AEncoding: TCryptoLibByteArray;
+      AMacKeySize: Int32);
   end;
 
 implementation
 
 { TIESParameters }
 
-constructor TIESParameters.Create(const derivation,
-  encoding: TCryptoLibByteArray; MacKeySize: Int32);
+constructor TIesParameters.Create(const ADerivation,
+  AEncoding: TCryptoLibByteArray; AMacKeySize: Int32);
 begin
   Inherited Create();
-  Fderivation := derivation;
-  Fencoding := encoding;
-  FmacKeySize := MacKeySize;
+  Fderivation := ADerivation;
+  Fencoding := AEncoding;
+  FmacKeySize := AMacKeySize;
 end;
 
-function TIESParameters.GetDerivationV: TCryptoLibByteArray;
+function TIesParameters.GetDerivationV: TCryptoLibByteArray;
 begin
-  result := System.Copy(Fderivation);
+  Result := System.Copy(Fderivation);
 end;
 
-function TIESParameters.GetEncodingV: TCryptoLibByteArray;
+function TIesParameters.GetEncodingV: TCryptoLibByteArray;
 begin
-  result := System.Copy(Fencoding);
+  Result := System.Copy(Fencoding);
 end;
 
-function TIESParameters.GetMacKeySize: Int32;
+function TIesParameters.GetMacKeySize: Int32;
 begin
-  result := FmacKeySize;
+  Result := FmacKeySize;
 end;
 
 end.

+ 14 - 14
CryptoLib/src/Crypto/Parameters/ClpIESWithCipherParameters.pas → CryptoLib/src/Crypto/Parameters/ClpIesWithCipherParameters.pas

@@ -15,7 +15,7 @@
 
 (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
 
-unit ClpIESWithCipherParameters;
+unit ClpIesWithCipherParameters;
 
 {$I ..\..\Include\CryptoLib.inc}
 
@@ -29,8 +29,8 @@ uses
 
 type
 
-  TIESWithCipherParameters = class(TIESParameters, IIESParameters,
-    IIESWithCipherParameters)
+  TIesWithCipherParameters = class(TIesParameters, IIesParameters,
+    IIesWithCipherParameters)
 
   strict private
   var
@@ -42,20 +42,20 @@ type
     /// <summary>
     /// Set the IES engine parameters.
     /// </summary>
-    /// <param name="derivation">
+    /// <param name="ADerivation">
     /// the optional derivation vector for the KDF.
     /// </param>
-    /// <param name="encoding">
+    /// <param name="AEncoding">
     /// the optional encoding vector for the KDF.
     /// </param>
-    /// <param name="macKeySize">
+    /// <param name="AMacKeySize">
     /// the key size (in bits) for the MAC.
     /// </param>
-    /// <param name="CipherKeySize">
+    /// <param name="ACipherKeySize">
     /// the key size (in bits) for the block cipher.
     /// </param>
-    constructor Create(const derivation, encoding: TCryptoLibByteArray;
-      macKeySize, CipherKeySize: Int32);
+    constructor Create(const ADerivation, AEncoding: TCryptoLibByteArray;
+      AMacKeySize, ACipherKeySize: Int32);
 
     /// <summary>
     /// Return the key size in bits for the block cipher used with the message
@@ -71,16 +71,16 @@ implementation
 
 { TIESWithCipherParameters }
 
-function TIESWithCipherParameters.GetCipherKeySize: Int32;
+function TIesWithCipherParameters.GetCipherKeySize: Int32;
 begin
   Result := FcipherKeySize;
 end;
 
-constructor TIESWithCipherParameters.Create(const derivation,
-  encoding: TCryptoLibByteArray; macKeySize, CipherKeySize: Int32);
+constructor TIesWithCipherParameters.Create(const ADerivation,
+  AEncoding: TCryptoLibByteArray; AMacKeySize, ACipherKeySize: Int32);
 begin
-  Inherited Create(derivation, encoding, macKeySize);
-  FcipherKeySize := CipherKeySize;
+  Inherited Create(ADerivation, AEncoding, AMacKeySize);
+  FcipherKeySize := ACipherKeySize;
 end;
 
 end.

+ 0 - 205
CryptoLib/src/Interfaces/ClpIESParameterSpec.pas

@@ -1,205 +0,0 @@
-{ *********************************************************************************** }
-{ *                              CryptoLib Library                                  * }
-{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
-{ *                 Github Repository <https://github.com/Xor-el>                   * }
-
-{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
-{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
-
-{ *                              Acknowledgements:                                  * }
-{ *                                                                                 * }
-{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
-{ *                           development of this library                           * }
-
-{ * ******************************************************************************* * }
-
-(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
-
-unit ClpIESParameterSpec;
-
-{$I ..\Include\CryptoLib.inc}
-
-interface
-
-uses
-  ClpIIESParameterSpec,
-  ClpIAlgorithmParameterSpec,
-  ClpCryptoLibTypes;
-
-type
-
-  /// <summary>
-  /// Parameter spec for an integrated encryptor, as in IEEE P1363a
-  /// </summary>
-  TIESParameterSpec = class sealed(TInterfacedObject, IAlgorithmParameterSpec,
-    IIESParameterSpec)
-
-  strict private
-  var
-    Fderivation, Fencoding, FNonce: TCryptoLibByteArray;
-    FmacKeySize, FcipherKeySize: Int32;
-    FusePointCompression: Boolean;
-
-  strict private
-    function GetDerivationV: TCryptoLibByteArray; inline;
-    function GetEncodingV: TCryptoLibByteArray; inline;
-    function GetMacKeySize: Int32; inline;
-    function GetCipherKeySize: Int32; inline;
-    function GetNonce: TCryptoLibByteArray; inline;
-    function GetPointCompression: Boolean; inline;
-
-  public
-
-    /// <summary>
-    /// Set the IES engine parameters.
-    /// </summary>
-    /// <param name="derivation">
-    /// the optional derivation vector for the KDF.
-    /// </param>
-    /// <param name="encoding">
-    /// the optional encoding vector for the KDF.
-    /// </param>
-    /// <param name="macKeySize">
-    /// the key size (in bits) for the MAC.
-    /// </param>
-    /// <param name="CipherKeySize">
-    /// the key size (in bits) for the block cipher.
-    /// </param>
-    /// <param name="Nonce">
-    /// an IV to use initialising the block cipher.
-    /// </param>
-    constructor Create(const derivation, encoding: TCryptoLibByteArray;
-      MacKeySize, CipherKeySize: Int32;
-      const Nonce: TCryptoLibByteArray); overload;
-
-    /// <summary>
-    /// Set the IES engine parameters.
-    /// </summary>
-    /// <param name="derivation">
-    /// the optional derivation vector for the KDF.
-    /// </param>
-    /// <param name="encoding">
-    /// the optional encoding vector for the KDF.
-    /// </param>
-    /// <param name="macKeySize">
-    /// the key size (in bits) for the MAC.
-    /// </param>
-    /// <param name="CipherKeySize">
-    /// the key size (in bits) for the block cipher.
-    /// </param>
-    /// <param name="Nonce">
-    /// an IV to use initialising the block cipher.
-    /// </param>
-    /// <param name="UsePointCompression">
-    /// whether to use EC point compression or not (false by default)
-    /// </param>
-    constructor Create(const derivation, encoding: TCryptoLibByteArray;
-      MacKeySize: Int32; CipherKeySize: Int32 = -1;
-      const Nonce: TCryptoLibByteArray = Nil;
-      UsePointCompression: Boolean = False); overload;
-
-    /// <summary>
-    /// Returns the derivation vector.
-    /// </summary>
-    /// <value>
-    /// the derivation vector.
-    /// </value>
-    property DerivationV: TCryptoLibByteArray read GetDerivationV;
-
-    /// <summary>
-    /// Returns the encoding vector.
-    /// </summary>
-    /// <value>
-    /// the encoding vector.
-    /// </value>
-    property EncodingV: TCryptoLibByteArray read GetEncodingV;
-
-    /// <summary>
-    /// Return the key size in bits for the MAC used with the message
-    /// </summary>
-    /// <value>
-    /// the key size in bits for the MAC used with the message
-    /// </value>
-    property MacKeySize: Int32 read GetMacKeySize;
-
-    /// <summary>
-    /// Return the key size in bits for the block cipher used with the message
-    /// </summary>
-    /// <value>
-    /// the key size in bits for the block cipher used with the message
-    /// </value>
-    property CipherKeySize: Int32 read GetCipherKeySize;
-
-    /// <summary>
-    /// Return the Nonce (IV) value to be associated with message.
-    /// </summary>
-    /// <value>
-    /// block cipher IV for message.
-    /// </value>
-    property Nonce: TCryptoLibByteArray read GetNonce;
-
-    /// <summary>
-    /// Return the 'point compression' flag.
-    /// </summary>
-    /// <value>
-    /// the point compression flag
-    /// </value>
-    property PointCompression: Boolean read GetPointCompression;
-
-  end;
-
-implementation
-
-{ TIESParameterSpec }
-
-constructor TIESParameterSpec.Create(const derivation,
-  encoding: TCryptoLibByteArray; MacKeySize, CipherKeySize: Int32;
-  const Nonce: TCryptoLibByteArray);
-begin
-  Create(derivation, encoding, MacKeySize, CipherKeySize, Nonce, False);
-end;
-
-constructor TIESParameterSpec.Create(const derivation,
-  encoding: TCryptoLibByteArray; MacKeySize: Int32; CipherKeySize: Int32;
-  const Nonce: TCryptoLibByteArray; UsePointCompression: Boolean);
-begin
-  Inherited Create();
-  Fderivation := derivation;
-  Fencoding := encoding;
-  FmacKeySize := MacKeySize;
-  FcipherKeySize := CipherKeySize;
-  FNonce := System.Copy(Nonce);
-  FusePointCompression := UsePointCompression;
-end;
-
-function TIESParameterSpec.GetCipherKeySize: Int32;
-begin
-  result := FcipherKeySize;
-end;
-
-function TIESParameterSpec.GetDerivationV: TCryptoLibByteArray;
-begin
-  result := System.Copy(Fderivation);
-end;
-
-function TIESParameterSpec.GetEncodingV: TCryptoLibByteArray;
-begin
-  result := System.Copy(Fencoding);
-end;
-
-function TIESParameterSpec.GetMacKeySize: Int32;
-begin
-  result := FmacKeySize;
-end;
-
-function TIESParameterSpec.GetNonce: TCryptoLibByteArray;
-begin
-  result := System.Copy(FNonce);
-end;
-
-function TIESParameterSpec.GetPointCompression: Boolean;
-begin
-  result := FusePointCompression;
-end;
-
-end.

+ 0 - 90
CryptoLib/src/Interfaces/ClpIIESParameterSpec.pas

@@ -1,90 +0,0 @@
-{ *********************************************************************************** }
-{ *                              CryptoLib Library                                  * }
-{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
-{ *                 Github Repository <https://github.com/Xor-el>                   * }
-
-{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
-{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
-
-{ *                              Acknowledgements:                                  * }
-{ *                                                                                 * }
-{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
-{ *                           development of this library                           * }
-
-{ * ******************************************************************************* * }
-
-(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
-
-unit ClpIIESParameterSpec;
-
-{$I ..\Include\CryptoLib.inc}
-
-interface
-
-uses
-  ClpIAlgorithmParameterSpec,
-  ClpCryptoLibTypes;
-
-type
-  IIESParameterSpec = interface(IAlgorithmParameterSpec)
-    ['{F83CD14B-C049-4878-8D78-0214FD9D2B8A}']
-
-    /// <summary>
-    /// Returns the derivation vector.
-    /// </summary>
-    /// <value>
-    /// the derivation vector.
-    /// </value>
-    function GetDerivationV: TCryptoLibByteArray;
-    property DerivationV: TCryptoLibByteArray read GetDerivationV;
-
-    /// <summary>
-    /// Returns the encoding vector.
-    /// </summary>
-    /// <value>
-    /// the encoding vector.
-    /// </value>
-    function GetEncodingV: TCryptoLibByteArray;
-    property EncodingV: TCryptoLibByteArray read GetEncodingV;
-
-    /// <summary>
-    /// Return the key size in bits for the MAC used with the message
-    /// </summary>
-    /// <value>
-    /// the key size in bits for the MAC used with the message
-    /// </value>
-    function GetMacKeySize: Int32;
-    property MacKeySize: Int32 read GetMacKeySize;
-
-    /// <summary>
-    /// Return the key size in bits for the block cipher used with the message
-    /// </summary>
-    /// <value>
-    /// the key size in bits for the block cipher used with the message
-    /// </value>
-    function GetCipherKeySize: Int32;
-    property CipherKeySize: Int32 read GetCipherKeySize;
-
-    /// <summary>
-    /// Return the Nonce (IV) value to be associated with message.
-    /// </summary>
-    /// <value>
-    /// block cipher IV for message.
-    /// </value>
-    function GetNonce: TCryptoLibByteArray;
-    property Nonce: TCryptoLibByteArray read GetNonce;
-
-    /// <summary>
-    /// Return the 'point compression' flag.
-    /// </summary>
-    /// <value>
-    /// the point compression flag
-    /// </value>
-    function GetPointCompression: Boolean;
-    property PointCompression: Boolean read GetPointCompression;
-
-  end;
-
-implementation
-
-end.

+ 0 - 54
CryptoLib/src/Interfaces/Crypto/Ciphers/ClpIIESCipher.pas

@@ -1,54 +0,0 @@
-{ *********************************************************************************** }
-{ *                              CryptoLib Library                                  * }
-{ *                Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe                    * }
-{ *                 Github Repository <https://github.com/Xor-el>                   * }
-
-{ *  Distributed under the MIT software license, see the accompanying file LICENSE  * }
-{ *          or visit http://www.opensource.org/licenses/mit-license.php.           * }
-
-{ *                              Acknowledgements:                                  * }
-{ *                                                                                 * }
-{ *      Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring     * }
-{ *                           development of this library                           * }
-
-{ * ******************************************************************************* * }
-
-(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
-
-unit ClpIIESCipher;
-
-{$I ..\..\..\Include\CryptoLib.inc}
-
-interface
-
-uses
-  ClpICipherParameters,
-  ClpISecureRandom,
-  ClpIAlgorithmParameterSpec,
-  ClpCryptoLibTypes;
-
-type
-  IIESCipher = interface(IInterface)
-    ['{DD112FD3-844A-4EF0-B9B8-22AFAEFB0881}']
-
-    procedure Init(ForEncryption: Boolean; const Key: ICipherParameters;
-      const engineSpec: IAlgorithmParameterSpec; const Random: ISecureRandom);
-
-    procedure ProcessBytes(const input: TCryptoLibByteArray); overload;
-    procedure ProcessBytes(const input: TCryptoLibByteArray;
-      inputOffset, inputLen: Int32); overload;
-
-    function DoFinal(const input: TCryptoLibByteArray)
-      : TCryptoLibByteArray; overload;
-
-    function DoFinal(const input: TCryptoLibByteArray;
-      inputOffset, inputLen: Int32): TCryptoLibByteArray; overload;
-
-    function DoFinal(const input: TCryptoLibByteArray;
-      inputOffset, inputLen: Int32; const output: TCryptoLibByteArray;
-      outputOffset: Int32): Int32; overload;
-  end;
-
-implementation
-
-end.

+ 23 - 23
CryptoLib/src/Interfaces/Crypto/Engines/ClpIIESEngine.pas → CryptoLib/src/Interfaces/Crypto/Engines/ClpIIesEngine.pas

@@ -15,7 +15,7 @@
 
 (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
 
-unit ClpIIESEngine;
+unit ClpIIesEngine;
 
 {$I ..\..\..\Include\CryptoLib.inc}
 
@@ -32,7 +32,7 @@ uses
 
 type
 
-  IIESEngine = interface(IInterface)
+  IIesEngine = interface(IInterface)
     ['{9FA0E287-9988-467D-9E00-3BECEE4A78C6}']
 
     function GetCipher: IBufferedBlockCipher;
@@ -41,61 +41,61 @@ type
     /// <summary>
     /// Initialise the encryptor/decryptor.
     /// </summary>
-    /// <param name="forEncryption">
+    /// <param name="AForEncryption">
     /// whether or not this is encryption/decryption.
     /// </param>
-    /// <param name="privParam">
+    /// <param name="APrivParam">
     /// our private key parameters
     /// </param>
-    /// <param name="pubParam">
+    /// <param name="APubParam">
     /// the recipient's/sender's public key parameters
     /// </param>
-    /// <param name="params">
+    /// <param name="AParams">
     /// encoding and derivation parameters, may be wrapped to include an IV
     /// for an underlying block cipher.
     /// </param>
-    procedure Init(forEncryption: Boolean; const privParam, pubParam,
-      params: ICipherParameters); overload;
+    procedure Init(AForEncryption: Boolean; const APrivParam, APubParam,
+      AParams: ICipherParameters); overload;
 
     /// <summary>
     /// Initialise the encryptor.
     /// </summary>
-    /// <param name="publicKey">
+    /// <param name="APublicKey">
     /// the recipient's/sender's public key parameters
     /// </param>
-    /// <param name="params">
+    /// <param name="AParams">
     /// encoding and derivation parameters, may be wrapped to include an IV
     /// for an underlying block cipher.
     /// </param>
-    /// <param name="ephemeralKeyPairGenerator">
+    /// <param name="AEphemeralKeyPairGenerator">
     /// the ephemeral key pair generator to use.
     /// </param>
-    procedure Init(const publicKey: IAsymmetricKeyParameter;
-      const params: ICipherParameters;
-      const ephemeralKeyPairGenerator: IEphemeralKeyPairGenerator); overload;
+    procedure Init(const APublicKey: IAsymmetricKeyParameter;
+      const AParams: ICipherParameters;
+      const AEphemeralKeyPairGenerator: IEphemeralKeyPairGenerator); overload;
 
     /// <summary>
     /// Initialise the decryptor.
     /// </summary>
-    /// <param name="privateKey">
+    /// <param name="APrivateKey">
     /// the recipient's private key.
     /// </param>
-    /// <param name="params">
+    /// <param name="AParams">
     /// encoding and derivation parameters, may be wrapped to include an IV
     /// for an underlying block cipher.
     /// </param>
-    /// <param name="publicKeyParser">
+    /// <param name="APublicKeyParser">
     /// the parser for reading the ephemeral public key.
     /// </param>
-    procedure Init(const privateKey: IAsymmetricKeyParameter;
-      const params: ICipherParameters;
-      const publicKeyParser: IKeyParser); overload;
+    procedure Init(const APrivateKey: IAsymmetricKeyParameter;
+      const AParams: ICipherParameters;
+      const APublicKeyParser: IKeyParser); overload;
 
-    function ProcessBlock(const &in: TCryptoLibByteArray; inOff, inLen: Int32)
+    function ProcessBlock(const AIn: TCryptoLibByteArray; AInOff, AInLen: Int32)
       : TCryptoLibByteArray;
 
-    property cipher: IBufferedBlockCipher read GetCipher;
-    property mac: IMac read GetMac;
+    property Cipher: IBufferedBlockCipher read GetCipher;
+    property Mac: IMac read GetMac;
   end;
 
 implementation

+ 2 - 2
CryptoLib/src/Interfaces/Crypto/Engines/ClpIPascalCoinIESEngine.pas → CryptoLib/src/Interfaces/Crypto/Engines/ClpIPascalCoinIesEngine.pas

@@ -15,7 +15,7 @@
 
 (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
 
-unit ClpIPascalCoinIESEngine;
+unit ClpIPascalCoinIesEngine;
 
 {$I ..\..\..\Include\CryptoLib.inc}
 
@@ -26,7 +26,7 @@ uses
 
 type
 
-  IPascalCoinIESEngine = interface(IIESEngine)
+  IPascalCoinIesEngine = interface(IIesEngine)
     ['{CEB707A3-6000-4771-A0F9-7C146B8DDE7A}']
 
   end;

+ 20 - 4
CryptoLib/src/Interfaces/ClpIAlgorithmParameterSpec.pas → CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIesCipherParameters.pas

@@ -15,15 +15,31 @@
 
 (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
 
-unit ClpIAlgorithmParameterSpec;
+unit ClpIIesCipherParameters;
 
-{$I ..\Include\CryptoLib.inc}
+{$I ..\..\..\Include\CryptoLib.inc}
 
 interface
 
+uses
+  ClpICipherParameters,
+  ClpIIESParameters;
+
 type
-  IAlgorithmParameterSpec = interface(IInterface)
-    ['{FBA69725-AEFF-4B99-92C0-1819E5DE2DA1}']
+  /// <summary>
+  /// Parameters for BufferedIesCipher Init: bundles private key, public key,
+  /// and IES parameters for engine.Init(forEncryption, priv, pub, iesParams).
+  /// </summary>
+  IIesCipherParameters = interface(ICipherParameters)
+    ['{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}']
+
+    function GetPrivateKey: ICipherParameters;
+    function GetPublicKey: ICipherParameters;
+    function GetIesParameters: IIesParameters;
+
+    property PrivateKey: ICipherParameters read GetPrivateKey;
+    property PublicKey: ICipherParameters read GetPublicKey;
+    property IesParameters: IIesParameters read GetIesParameters;
   end;
 
 implementation

+ 2 - 2
CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIESParameters.pas → CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIesParameters.pas

@@ -15,7 +15,7 @@
 
 (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
 
-unit ClpIIESParameters;
+unit ClpIIesParameters;
 
 {$I ..\..\..\Include\CryptoLib.inc}
 
@@ -27,7 +27,7 @@ uses
 
 type
 
-  IIESParameters = interface(ICipherParameters)
+  IIesParameters = interface(ICipherParameters)
     ['{F95232BB-594C-492E-AF63-C5A6822C96FD}']
 
     function GetDerivationV: TCryptoLibByteArray;

+ 2 - 2
CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIESWithCipherParameters.pas → CryptoLib/src/Interfaces/Crypto/Parameters/ClpIIesWithCipherParameters.pas

@@ -15,7 +15,7 @@
 
 (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
 
-unit ClpIIESWithCipherParameters;
+unit ClpIIesWithCipherParameters;
 
 {$I ..\..\..\Include\CryptoLib.inc}
 
@@ -27,7 +27,7 @@ uses
 
 type
 
-  IIESWithCipherParameters = interface(IIESParameters)
+  IIesWithCipherParameters = interface(IIesParameters)
     ['{77F38EA8-08F2-4D0D-A8E9-F3796DCCCA54}']
 
     function GetCipherKeySize: Int32;

+ 0 - 2
CryptoLib/src/Math/ClpBigInteger.pas

@@ -2270,7 +2270,6 @@ end;
 
 function TBigInteger.Int32ValueExact(): Int32;
 begin
-  // Match C# IntValueExact: if (BitLength > 31) throw; else return IntValue
   if BitLength > 31 then
   begin
     raise EArithmeticCryptoLibException.Create(SBigIntegerOutOfIntRange);
@@ -2281,7 +2280,6 @@ end;
 
 function TBigInteger.Int64ValueExact(): Int64;
 begin
-  // Match C# LongValueExact: if (BitLength > 63) throw; else return Int64Value
   if BitLength > 63 then
   begin
     raise EArithmeticCryptoLibException.Create(SBigIntegerOutOfLongRange);