Giter Club home page Giter Club logo

cryptolib4pascal's Introduction

CryptoLib4Pascal: Crypto for Modern Object Pascal License

CryptoLib4Pascal is an Object Pascal cryptographic library released under the permissive MIT License.

CryptoLib4Pascal's goal is to be the best option for cryptography in Object Pascal by offering cryptographic recipes and primitives to Object Pascal developers.

Development is coordinated on GitHub and contributions are welcome. If you need help, please open an issue here.

Available Algorithms

Symmetric Encryption


Block Ciphers
  • AES (128, 192, and 256)

  • Rijndael

  • Blowfish

  • Speck

Stream Ciphers
  • ChaCha

  • (X)Salsa20

Block Cipher Modes Of Operation

  • ECB

  • CBC

  • CFB

  • CTR

  • CTS

  • OFB

  • SIC

Block Cipher Padding Schemes

  • ISO 10126-2

  • ISO 7816-4

  • Bit (ISO/IEC 9797-1)

  • PKCS#5

  • PKCS#7

  • TBC (Trailing Bit Complement)

  • ANSI X9.23

  • Zero

Asymmetric Cryptography


  • DSA

  • (DET)ECDSA (supported curves: NIST, X9.62, SEC2, Brainpool)

  • ECNR

  • ECSchnorr

  • EdDSA (Ed25519, Ed25519Blake2B)

Key Agreement/Exchange


  • DH

  • ECDH

  • ECDHC

  • X25519

Key Derivation Functions


  • HKDF

  • KDF1

  • KDF2

Password Hashing Schemes (Password Based Key Derivation Functions)

  • PBKDF2

  • Argon2 (2i, 2d and 2id variants)

  • Scrypt

MAC


  • HMAC (all supported hashes)

  • KMAC (KMAC128, KMAC256)

Hashes


  • MD2

  • MD4

  • MD5

  • SHA-1

  • SHA-2 (224, 256, 384, 512, 512-224, 512-256)

  • Gost3411

  • Gost3411-2012 (256, 512)

  • RIPEMD (128, 160, 256, 256, 320)

  • Tiger

  • WhirlPool

  • Blake2B (160, 256, 384, 512)

  • Blake2S (128, 160, 224, 256)

  • SHA-3 (224, 256, 384, 512)

  • Keccak (224, 256, 288, 384, 512)

XOF (Extendable Output Function)


  • Shake (Shake-128, Shake-256)

Other Useful Things


  • RNG wrappers for system RNG

  • ASN1 Parsing Utilities

  • Base Encoding and Decoding Utilities

Compile-Time Dependencies


Supported Compilers


  • FreePascal 3.2.0+

  • Delphi Tokyo+

Supported / Tested OSes


Tested OS boxes are checked

    • Windows XP+
    • Linux (Including Android and Raspberry PI)
    • Mac OS X
    • iOS 2.0+
    • (Oracle) Solaris
    • OpenBSD
    • FreeBSD
    • NetBSD
    • DragonFlyBSD

Acknowledgements


Tip Jar


  • 💵 Bitcoin: 1MhFfW7tDuEHQSgie65uJcAfJgCNchGeKf
  • 💶 Ethereum: 0x6c1DC21aeC49A822A4f1E3bf07c623C2C1978a98
  • 💷 Pascalcoin: 345367-40

cryptolib4pascal's People

Contributors

tondrej avatar xor-el avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cryptolib4pascal's Issues

Consider adding more random nuber generation algorithms

There are quite good never algorithms out there, but not too many Delphi/PAscal implementations of them.

If find time and feel that they would benefit library and community, that is my suggestion how to make it better.

Installer

Is there a way to automate de installer on Delphi?
Its a lot of file to include manually on search path

Sample for calculate a session key with curve25519

Hello,

I'm new with CryptoLib4Pascal and I can't find an example to obtain a session key using curve25519.

With a partial pascal porting of tweet-nacl (https://github.com/krisztianpinter/curve25519-delphi), A and B set their keys with something like pubKey_A:=crypto_scalarmult_base(privKey_A) and pubKey_B:= crypto_scalarmult_base(privKey_B).

Next A and B calculate the common session key with sessionKey:=crypto_scalarmult(privKey_A,pubKey_B) and sessionKey:=crypto_scalarmult(privKey_B,pubKey_A)

I looked at UsageExamples but I can't figure out how to do something similar.

Thanks and Regards
Raffaele


Just found that there are other examples than those in UsageExamples.
Thank you anyway

SSH ECDH problem

Describe the bug
i got this information from PUTTY

dumped information :

Event Log: Doing ECDH key exchange with curve Curve25519 and hash SHA-256 (unaccelerated)

Event Log: Doing ECDH my PUB key :

length 32

423EBB48BE9425B867005C4F269C369CCA11D514C30A7276C8E3193DC2FAD355

Event Log: my Private Key:

length of int 32

B81895A577E387CBD485E41D40FDF838EA087CA0F80895E00B2CBC29ECDAD57A

Event Log: get from packget: hostkeydata :

length 149

000000077373682D72736100000001230000008100C7576DF22171A80402819B89F3D7A9F3AFC4685F048614351ACBB1446DD2D273BA910D0C4DC7CF2583AA676DDA653A9C17DD6F5DA010BEC5C8E25B9117694276D82E078922A785B86E90D78DDFB383158381E8A3F99B97018F095EDC374F2EACE724222C97629CD19E6A35F25018D425A23205228171C08E8183F3A43E1DFABD

Event Log: Doing ECDH get my PUB key :

length 32

423EBB48BE9425B867005C4F269C369CCA11D514C30A7276C8E3193DC2FAD355

Event Log: get from packget: remote pub key :

length 32

00D1F0E49F1FC6F6C69658A504DFD37EF4E7736BE32E4E119531F28091004C5E

Event Log: get from packget: remote pub key to mpint

length of int 32

00D1F0E49F1FC6F6C69658A504DFD37EF4E7736BE32E4E119531F28091004C5E

Event Log: calculated K:

length of int 32

5C83053209F541B4DD1135D14690312E2C3396EAA8ABC48068854E3CBCDAFC07


the shared secret should be : 5C83053209F541B4DD1135D14690312E2C3396EAA8ABC48068854E3CBCDAFC07

To Reproduce
but my test code below do not get the same shared secret, do i miss something?

procedure testCurve25519;
var
s:string;
priv,remotepub,mypub,encryptkey,tmp:TBytes;
n:TCryptoLibUInt32Array;
var
kpGen: IAsymmetricCipherKeyPairGenerator;
kpA, kpB: IAsymmetricCipherKeyPair;
agreeA, agreeB: IX25519Agreement;
secretA, secretB: TBytes;
FRandom: ISecureRandom;
privateKey: IX25519PrivateKeyParameters;
publicKey,kpBpublicKey: IX25519PublicKeyParameters;
begin
FRandom := TSecureRandom.Create();
kpGen := TX25519KeyPairGenerator.Create() as IX25519KeyPairGenerator;
kpGen.Init(TX25519KeyGenerationParameters.Create(FRandom)
as IX25519KeyGenerationParameters);
//if (not AreEqual(secretA, secretB)) then
//begin
// Fail('X25519 agreement failed');
//end;
s:='B81895A577E387CBD485E41D40FDF838EA087CA0F80895E00B2CBC29ECDAD57A';
priv := THex.Decode(s);
privateKey := TX25519PrivateKeyParameters.Create(priv,0);
publicKey := privateKey.GeneratePublicKey();
kpA := TAsymmetricCipherKeyPair.Create(publicKey, privateKey);
tmp:=publicKey.GetEncoded();
s:=THex.Encode(tmp);
writeln(StdOut,'my pub from priv:',s);
s:='00D1F0E49F1FC6F6C69658A504DFD37EF4E7736BE32E4E119531F28091004C5E';
remotepub := THex.Decode(s);
kpBpublicKey:=TX25519PublicKeyParameters.Create(remotepub,0);
agreeA := TX25519Agreement.Create();
agreeA.Init(kpA.Private);
System.SetLength(secretA, agreeA.AgreementSize);
agreeA.CalculateAgreement(kpBpublicKey, secretA, 0);
s:=THex.Encode(secretA);
writeln(StdOut,'secretA:',s);
System.SetLength(encryptkey, TX25519.PointSize);
System.SetLength(mypub, TX25519.PointSize);
writeln(StdOut,'test private to public');
TX25519.ScalarMultBase(priv, 0, mypub, 0);
s:=THex.Encode(mypub);
writeln(StdOut,'my pub:',s);
TX25519.ScalarMult(priv, 0,remotepub , 0, encryptkey, 0);
s:=THex.Encode(encryptkey);
writeln(StdOut,'shared secret:',s);
end;
OUTPUT:

my pub from priv:423EBB48BE9425B867005C4F269C369CCA11D514C30A7276C8E3193DC2FAD355

secretA:07FCDABC3C4E856880C4ABA8EA96332C2E319046D13511DDB441F5093205835C

test private to public

my pub:423EBB48BE9425B867005C4F269C369CCA11D514C30A7276C8E3193DC2FAD355

shared secret:07FCDABC3C4E856880C4ABA8EA96332C2E319046D13511DDB441F5093205835C

Expected behavior
Shared secret should same as putty?
I am making an SSH client.

Environment (please complete the following information):

  • OS: putty 0.74 in Windows, openssh 8.4p1 in Linux
  • Compiler FreePascal 3.0.4
  • Package Version 4

Sample for AES128 Encryption

Hello.

I need AES128, CBC, PKCS7Padding Encryption.
Key & IV already fixed.

sure, i found AES256 encryption function in .Sample,
but I am stupid, I can not change to AES128 encrtypion code.

Please provide a sample for AES128/CBC/PKCS7Padding/(Key & IV already fixed).
(I do not know effect exist or not, anyway Char-Set decide as UTF-8)

Thanks & Regards,

Tbytes to BigInteger

Hi,
Could you please tell me why I get assert:

procedure Test;
var
  arrBytes: array[0..15] of byte = (159,245,94,199,119,153,43,128,135,251,91,211,154,145,184,255);,202,69,245,240,80,20};
  aBytes: TBytes;
  r, s: TBigInteger;
begin
  SetLength(aBytes, Length(arrBytes));
  Move(arrBytes[0], aBytes[0], Length(arrBytes));
  r := TBigInteger.Create(aBytes, 0, 16);
  s := TBigInteger.Create(TConverters.ConvertBytesToHexString(aBytes, false), 16);
  Assert(r.Equals(s), 'BigIntegers are not equal');
end;

  • OS: Windows
  • Compiler FreePascal 3.0.4

S contains the right value, but why R is wrong? Thanks.

Best regards,
Alex

About ed25519 signature verification

Is your feature request related to a problem? Please describe.
In SSH, I got remote public key, remote signature with 64 bytes length.
But look into your ed25518signer, I provide them, but verification always fail.
What I did is

  1. Ted25519.create;
  2. Ted25519signer.create with above;
  3. Ted25519publickeyparameters.create with remote public key;
  4. Verify signature with remote signature;

Describe the solution you'd like
Please provide the step of verification.

Simple examples of usage.

Hi Xor-el! I really want to use cryptolib4pascal, but i have no idea how to use it. The unit test a very complicated. Although i think i can figure it by just delving into the unit tests, i think it would be better if you wrote some simpler examples. At the moment it would be just easier to use DCPCrypt but i would not have the flexibility of Cryptolib4pascal.

Sample for simple AES encryptions

Hello,

I am already using your libraries and thank you for making them available. I had no problem until today. Today, I had the need to encrypt a file using AES/CBC/PKCS7PADDING 256bits.

My existing code is something like below. However, that only encrypts data from TBytes

uses
  System.NetEncoding,
  ClpIBufferedCipher,
  ClpCipherUtilities,
  ClpIParametersWithIV,
  ClpParametersWithIV,
  ClpParameterUtilities,
  ClpEncoders;

//------------------------------------------------------------------------------
function EncryptAESCBC256WithKeyIV(const Key, IV: TBytes; const PlainText: string; out CryptBase64Text: string): Boolean;
var
  Cipher: IBufferedCipher;
  KeyParametersWithIV: IParametersWithIV;
  KeyBytes: TBytes;
  IVBytes: TBytes;
  Buf: TBytes;
  CryptBytes: TBytes;
begin
  try
    SetLength(KeyBytes, Length(Key)); // SizeOf() in Delphi behaves strange. Length() is much more stable even for arrays
    Move(Key[0], Pointer(KeyBytes)^, Length(Key));

    SetLength(IVBytes, Length(IV));
    Move(IV[0], Pointer(IVBytes)^, Length(IV));

    Cipher := TCipherUtilities.GetCipher('AES/CBC/PKCS7PADDING');
    KeyParametersWithIV := TParametersWithIV.Create(TParameterUtilities.CreateKeyParameter('AES', KeyBytes), IVBytes);
    Cipher.Init(True, KeyParametersWithIV); // init encryption cipher

    Buf := TEncoding.UTF8.GetBytes(PlainText);
    CryptBytes := Cipher.DoFinal(Buf);

    CryptBase64Text := TNetEncoding.Base64.EncodeBytesToString(CryptBytes);
  except
    on E: Exception do
    begin
      ALog.LogError('EncryptAESCBC256WithKeyIV(): ' + E.Message);
      Exit(False);
    end;
  end;
  Result := True;
end;

I believe, it will be helpful to have simple example(s) (nothing like elliptic curves, etc) for people like me who have very simple and basic needs as to encryption and willing to use your libraries.

I also appreciate if you can provide a simple way of encrypting a file. Possibly using one TFileStream class for input and one for output as parameter.

Just a side note, above code is from Delphi, I am trying to solve a problem on Linux (ARM platform) with file encryption, now. So, I will be using Lazarus for that matter.

Thanks & Regards,
Ertan

Several compilation errors

Hello, I can't compile the package again because there are several errors:

const
  EmptyBytesNil: TCryptoLibCustomByteArrayBuffer = (FData: Nil; FLength: 0;
    FIsNil: True);
[DCC Error] ClpCryptoLibTypes.pas(226): E2071 This type cannot be initialized

whether to replace :
var
  EmptyBytesNil: TCryptoLibCustomByteArrayBuffer = (FData: Nil; FLength: 0;
    FIsNil: True); 
???


Create(Int32(TThread.GetTickCount)); // Can be replaced by windows.GetTickCount ?
[DCC Error] ClpRandom.pas(108): E2003 Undeclared identifier: 'GetTickCount'
  if Supports(FHash, IXOF) then // What the  IXOF ???

  begin
    LXOFSizeInBits := (System.Length(output) - outOff) * 8;
    (FHash as IXOF).XOFSizeInBits := LXOFSizeInBits;
    Limit := LXOFSizeInBits shr 3;
  end
  else
  begin
    Limit := GetDigestSize;
  end;
[DCC Error] ClpDigest.pas(178): E2003 Undeclared identifier: 'IXOF'

HMAC-SHA256 help needed

Hello,

I am using Delphi 11.3 and trying to generate HMAC-SHA256. Samples codes only has single example to HMAC for PascalCoin. I came up with following code and it gives me compile error

uses
  ClpIDigest,
  ClpIMac,
  ClpDigestUtilities,
  ClpMacUtilities,
  ClpICipherParameters;

procedure TForm1.Button1Click(Sender: TObject);
var
  DigestMACInstance: IMac;
  Parameters: IChiperParameters; // [dcc32 Error] Unit1.pas(37): E2003 Undeclared identifier: 'IChiperParameters'
  LHMACBytes: TBytes;
begin
  DigestMACInstance := TMacUtilities.GetMac('HMAC-SHA256');
  // I believe Parameters to be assigned with my secret key and data to be hashed here
  DigestMACInstance.Init(Parameters);
  LHMACBytes := DigestMACInstance.DoFinal();
end;

I also saw TMacUtilities has direct reading of HMAC value which is easier to use in code but my problem is also valid for that use case as I need to pass parameters.

When I check ClpICipherParameters.pas it actually has empty interface defined in it.

I could not figure out my mistake. Any help is appreciated.

Thanks & Regards,
Ertan

Decrypt function customize fail, advice to me. plz.

Hello.

I am fail a Decrypt.

i need AES128 with fixed Key & IV. no SALT.
so, i customize UsageSample's AES256CBC Encrypt & Decrypt function like bottom.

my Encrypt function work very well. i confirm it make same result as my partner's result.
but, my Decrypt function always raise error. not wrong result, just can not make result.
(Key & IV is 16Character like '1234567890123456')

if original PlainText length < 32 then raise EDataLengthCryptoLibException.
(FbufOff <> blockSize(16) at TPaddedBufferedBlockCipher.Create)
if original PlainText length >= 32 then raise EInvalidCipherTextCryptoLibException.
(input array's Last is 0 or over16 at TPkcs7Padding.PadCount)
(decrypt function's input is cipheredText)

what is my mistake? what needs to be fixed?

------------------------------- my source code ( i don't know how make box, sorry) ----------------------
unit XorelCrypt;

interface

uses
System.SysUtils,
ClpIParametersWithIV, ClpIBufferedCipher, ClpCipherUtilities, ClpParametersWithIV,
ClpParameterUtilities, ClpConverters, ClpEncoders;

function XorelAESEncrypt( sPlain, sKey, sIV : string; out vCypher:string): boolean;
function XorelAESDecrypt( sCipher, sKey, sIV : string; out sPlain: string): Boolean;

implementation

function XorelAESEncrypt(sPlain, sKey, sIV: string; out vCypher:string): boolean;
var
PlainBytes, KeyBytes, IVBytes, BufBytes: TBytes;
KeyParametersWithIV: IParametersWithIV;
cipher: IBufferedCipher;
LBlockSize, LBufStart, Count: Int32;
begin
result := False;
vCypher := '';

PlainBytes := TConverters.ConvertStringToBytes( sPlain, TEncoding.UTF8);
KeyBytes := TConverters.ConvertStringToBytes( sKey, TEncoding.UTF8);

IVBytes := TConverters.ConvertStringToBytes( sIV, TEncoding.UTF8);

// remove Get Key & IV because it is Fixed.
cipher := TCipherUtilities.GetCipher('AES/CBC/PKCS7PADDING');
KeyParametersWithIV := TParametersWithIV.Create
(TParameterUtilities.CreateKeyParameter('AES', KeyBytes), IVBytes);

cipher.Init(True, KeyParametersWithIV); // init encryption cipher
LBlockSize := cipher.GetBlockSize;

System.SetLength(BufBytes, System.Length(PlainBytes) + LBlockSize);

LBufStart := 0;

Count := cipher.ProcessBytes(PlainBytes, 0, System.Length(PlainBytes), BufBytes,
LBufStart);
System.Inc(LBufStart, Count);
Count := cipher.DoFinal(BufBytes, LBufStart);
System.Inc(LBufStart, Count);

System.SetLength(BufBytes, LBufStart);

vCypher := TBase64.Encode( BufBytes);
result := True;
end;

function XorelAESDecrypt(sCipher, sKey, sIV: string; out sPlain: string): Boolean;
var
CipherBytes, KeyBytes, IVBytes, BufBytes : TBytes;
KeyParametersWithIV: IParametersWithIV;
cipher: IBufferedCipher;
LBufStart, LSrcStart, Count: Int32;
begin
result := False;
sPlain := '';

CipherBytes := TConverters.ConvertStringToBytes( sCipher, TEncoding.UTF8);
KeyBytes := TConverters.ConvertStringToBytes( sKey, TEncoding.UTF8);
IVBytes := TConverters.ConvertStringToBytes( sIV, TEncoding.UTF8);

// remove Get Key & IV because it is Fixed.
LSrcStart := 0;

cipher := TCipherUtilities.GetCipher('AES/CBC/PKCS7PADDING');
KeyParametersWithIV := TParametersWithIV.Create
(TParameterUtilities.CreateKeyParameter('AES', KeyBytes), IVBytes);

cipher.Init(False, KeyParametersWithIV); // init decryption cipher

System.SetLength(BufBytes, System.Length(CipherBytes));

LBufStart := 0;

Count := cipher.ProcessBytes(CipherBytes, LSrcStart, System.Length(CipherBytes)
- LSrcStart, BufBytes, LBufStart);
System.Inc(LBufStart, Count);
Count := cipher.DoFinal(BufBytes, LBufStart);
System.Inc(LBufStart, Count);

System.SetLength(BufBytes, LBufStart);

sPlain := TConverters.ConvertBytesToString( BufBytes, TEncoding.UTF8);
result := True;
end;

end.

Thanks & Regards,

Circular unit reference to 'ClpBigInteger'

Hi, I try using the Delphi example, after adding needed unit search path, Error stop me with message like below:

[dcc32 Fatal Error] ClpAsn1Objects.pas(33): F2047 Circular unit reference to 'ClpBigInteger'

Do you have any hint ?

Using this in RAD Studio 11

This is black magic to me. How do I use this in RAD Studio 11? I added CryptoLib to "Project -> Options -> Delphi Compiler -> Search Path" and enabled "Link with runtime packages", but I don't know how to start using it in the code.
Is there any instruction for this?

GE

Topic: Get IV in AES256 CBC Decryption.

I´m working with your AES256 CBC Encryption and it´s working great. But i can´t find any option, to get the IV, with i can decrypt the encryptet text with other AES256 programs. How does the IV get calculated? Or how can i get the IV? Some help would be great!

Cryptographically-secure pseudorandom number generator - CPRNG

Hello,

I could not be sure if there is cryptographically-secure pseudorandom number generator available in the library. I see "RNG wrappers for system RNG" is available, but I am not sure if that is the same thing.

I very much appreciate file names to check for examples for the RNG in the library even it is not cryptographically-secure.

What I am trying to do is to generate random IV for AES/CBC/PCKS#7 256 bit encryption/decryption.

I also read there are some ways to protect that random generated IV for replay attack attempts. I am not expert in anyway, but I can try to build something by researching and reading if library have helper functions for such.

Thanks & Regards,
Ertan

Compile error.

** Help me **
When I run CryptoLib.Tests, I got below messages in ClpDigest file.

[dcc32 Error] ClpDigest.pas(178): E2003 Undeclared identifier: 'IXOF'
[dcc32 Error] ClpDigest.pas(181): E2015 Operator not applicable to this operand type
[dcc32 Error] ClpDigest.pas(215): E2003 Undeclared identifier: 'Clone'
[dcc32 Fatal Error] ClpDigestUtilities.pas(268): F2063 Could not compile used unit 'ClpDigest.pas'
Failed

Source code

function TDigest.DoFinal(const output: TCryptoLibByteArray;
outOff: Int32): Int32;
var
buf: TCryptoLibByteArray;
Limit, LXOFSizeInBits: Int32;
begin

if Supports(FHash, IXOF) then
begin
LXOFSizeInBits := (System.Length(output) - outOff) * 8;
(FHash as IXOF).XOFSizeInBits := LXOFSizeInBits;
Limit := LXOFSizeInBits shr 3;
end

Because of it, I can't compile this. Please let me what's the matter.

Example with CryptoJS AES

Hi, there's a JavaScript library called CryptoJS, that supports several algorithms.

If possible, you can add a simple example, on how to decrypt using your library?

CryptoJS
https://cryptojs.gitbook.io/docs/#the-cipher-algorithms

var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
​
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");

CryptoJS supports AES-128, AES-192, and AES-256. It will pick the variant by the size of the key you pass in. If you use a passphrase, then it will generate a 256-bit key.

I asked in the forum for help, but didn't find a good response, googling I found your packages.

Here is more information
https://forum.lazarus.freepascal.org/index.php/topic,54581.0.html

And sample code in Java that does the thing.

Thanks and have a nice day.

Compilation error in Lazarus

When i try to add the Package in Lazarus
i get compilation Error "clpcryptolibtypes.pas(74,70) Error: Message recordind not yet supported"

To Reproduce
Steps to reproduce the behavior:

  1. Go to 'Package->Open package file (*.lpk)'
  2. Select 'CryptoLib4PascalPackage.lpk'
  3. Click 'Compile'
  4. See error

Screenshots

cryptoliberror

Environment (please complete the following information):

  • OS: [Windows 7 Professional 64 bit]
  • Compiler [FreePascal 3.0.4]

Additional context
same error in IDE and wheh i compile from command line

Lazarus form examples?

My problem is limited documentation and not understanding the example applications given.

I would like a simple example application that possibly shows how to generate bitcoin addresses. I also do not understand fully how to include the neccesary files in my project, which is more of an ignorance issue of mine and understanding of lazarus i suppose.

If we could get some clear examples in a simple form application that would be great. Maybe how to generate bitcoin addresses and also maybe an example of encrypting a memo's text with various crypto algorithms and methods to decrypt.

SHA256WITHDSA verify problem

Hi,

I'm using your library to verify a DSA signature. Generally, this works fine, but I have one signature which causes trouble. When I call Signer.VerifySignature(sigBytes), I get a silent EArgumentCryptoLibException:

Value out of range, "x"

The result is then false, but it should be true. The same signature + content verifies successfully in a java project, so the signature + content are definately valid.

My analysis:
When parsing the ASN.1 structure of the signature, the r value is a TBigInteger with a sign of -1. There is a ClpSignersEncodings.TStandardDsaEncoding.CheckValue(const n, x: TBigInteger) function which raises this exception when the sign is negative.

I have successfully validated the signature with this two dirty hacks:

  • ClpBigInteger.TBigInteger.ParseBytes(): When r gets created, there is a check if the first byte is negative. Go the else-branch (even it is indeed negative)!
  • ClpSignersEncodings.TStandardDsaEncoding.Decode(): In the end, exit this function as if the both arrays were equal (they are not).

Then the validation succeeds! I have no clue what I am doing, but maybe this helps you finding the bug :-)

To Reproduce
Here is a short TestCase with two invocations. The first with a working signature, the second with the signature which causes trouble.

uses
  ClpIDsaPublicKeyParameters,
  ClpISigner,
  ClpSignerUtilities,
  ClpBigInteger,
  ClpDsaParameters,
  ClpDsaPublicKeyParameters,

  HlpConverters;

const
  SIGNATURE_FAIL =
    '3044022091481D2DD4902030BE5E941DC41D51051D38C8D6B52BD638F166AA0B285FD4540220729B054A4C1977D7F423FCCCE8531AB77DA4F4871415B948FA9FFC43B1653282';

  CONTENT_FAIL =
    '789C0B8D77F3718D30343630B4304FDAC4D0F690F7A05A4789A8204723AB4C8BF366ADB3338A5E2DE06A60E09B76E8C9B317A7EE70ACBB74E326238BCB753B4606A552898BEA218B3DCC7C2C5628275E3C1D27176BB4F8C2E7'+
    'DF17263B444573CF9EAD9D1825EDBDF8C422E3C9DCC5D1C6AB272F74CAE6F62EF404099EACDAECCD7991F16167E3C1C64F56AB8A16063A0969090639694D9A1964A41864A59554582555A59518945495941864E5E921C720C3'+
    'D0BA809391415572E3D487074F4E5D7AC6C0C0C2202CD4C010489B33A43030303032A9ADF431972861BF2051665BC4C0605B2C011465000972DC61E39528AB926B00722CB0A9B080AA10CA040088455F38';

  SIGNATURE_OK =
    '30440220782E2FE184A1D85E89E9338B298EC61AEBA248CE722056CA940A967C8A1D391202206E2C628C4FCEA91BA35216A0A350F894DE5EBD7B8909920FDE947FEEDE0E20C4';

  CONTENT_OK =
    '789C01BC0043FF555F464C455831333031383862B20086E10DC125EA2815110881051C844464D985668E23A00A80000E96C2E4E6E8CADC08AED2D8D9010444D7BE0100221CE610EA559B64364C38A82361D1CB5E1E5D32A3D0'+
    '979BD099C8426B0B7373432B4B6852932BABA3634B733B2B715AB34B09D101E18981C181F1424221521291521292A17A3A920A11525A095282314952B20A49529952826278083001A4C38AE5BB303ACE700380070014B00240'+
    '400F537570657220537061727072656973C41E4A03';

  PARAM_Y =
    '2071026581109650758038184064186458876296283481300943403866509942342382524620713451396343254114684899675018096590369661320483283915891166582478643454906082539533084932998847762533'+
    '5608491474738708319155141091176484174426011647105714888522392044284457605524311380058563471942453792467869956630831044794802346458000950850660797317292702519780588741916026340669'+
    '3620012965050922147558298228550935029104266071742567822000080296983419837677125515674745912823376511707389352243244256981176594257823975113333238642501605713186198500548884663216'+
    '55183209104790133727137773539483537009121119915647022479430130140834128010355366147';

  PARAM_P =
    '3017316225751025747816503856735074390137150438484287902337126460736744030289225070797062368697742354219140574539404572855291510404700630125513899004636916104465988521873694530966'+
    '1318177566530870929805256382987168067340008563174311414346376485783727860627287576374105590638940189925715546485395628902605554021519590402931608393003737437115405244576740720698'+
    '4835770992100788644604476304620720569870221703221752857037022257117195563165249290086072514593243867291836699225079470118050740478512600855228566314481165933907549303663373092953'+
    '25310946756575679469440910701253806730076290075220214443090215694678030619287443651';

  PARAM_Q =
    '89726923024951955097649575600463773741813068174113684889543146019116433923879';

  PARAM_G =
    '6682738806820039844008521695401888626604434767682364664746866004152999420930735095644239980782167926920540357506540943531558003772634839218334759316089889548468135218808036392037'+
    '2011689222919790333697690344631663740976611841320173892965305518127096861572682348179792158029674307464324521180906853686018459823737125128895604673978691732918869443789114925806'+
    '5472811992020860821346955758135422858848014563792522516932207263405005445975349224466539540552903706733887641939394032980403211285416125003974316524504106159538430710214970562737'+
    '4089518329951756701893447901613868789330561624574500181839826906305067813553340963';

function TestCase(const Content, Signature: string): Boolean;
   var
    Signer: ISigner;
    PubKey: IDSAPublicKeyParameters;
    msgBytes, sigBytes: TBytes;
   begin
    sigBytes := TConverters.ConvertHexStringToBytes(Signature);
    msgBytes := TConverters.ConvertHexStringToBytes(Content);

    PubKey := TDsaPublicKeyParameters.Create(
      TBigInteger.Create(PARAM_Y),
      TDsaParameters.Create(
        TBigInteger.Create(PARAM_P),
        TBigInteger.Create(PARAM_Q),
        TBigInteger.Create(PARAM_G)
      )
    );

    Signer := TSignerUtilities.GetSigner('SHA256WITHDSA');

    Signer.Init(False, PubKey);
    Signer.BlockUpdate(msgBytes, 0, Length(msgBytes));

    result := Signer.VerifySignature(sigBytes);
   end;

procedure TForm1.Button1Click(Sender: TObject);
   begin
    if not TestCase(CONTENT_OK, SIGNATURE_OK) then ShowMessage('Case 1 failed');
    if not TestCase(CONTENT_FAIL, SIGNATURE_FAIL) then ShowMessage('Case 2 failed');
   end;

Expected behavior
The two TestCase invocations should both return true.

Environment:

  • OS: Win32 & Android
  • Compiler: Delphi 10.4
  • Package Version trunk

Thanks!
Dominik

Cannot compile - HlpBlake2B.pas

Delphi 10.3.3, target Win32, very latest sources from git.

I have following in my uses. Not sure which unit actually triggers, so putting all my uses here.

uses
  ClpIBufferedCipher,
  ClpCipherUtilities,
  ClpIParametersWithIV,
  ClpParametersWithIV,
  ClpParameterUtilities,
  ClpEncoders;

No code needed, just try to compile and you will get
[dcc32 Fatal Error] HlpBlake2B.pas(13): F2613 Unit 'HlpIBlake2BParams' not found.

I remember (might be mistaken) that not found file is removed sometime back.

Thanks.

Error TECPrivateKeyParameters create 'Scalar is not in the interval[1, n-1]'

hello.
I need to calculate the ECDH ('secp256k1) shared secret, but I have problem when I create a Private key Parameters with the hex value of the private key of the server.
When I create TECPrivateKeyParameters always get this error message 'Scalar is not in the interval[1, n-1]'
this is the code of my test project:

procedure TFrmMain.Button5Click(Sender: TObject);
const
  SERVER_PRIVATE_KEY  = 'D295A6B1CC85A489EF49C28104DF254483734E54CC949315095D04E8891D3299';
var
  FCurve: IX9ECParameters;
  FRandom: ISecureRandom;
  domain: IECDomainParameters;
  generator: IECKeyPairGenerator;
  keygenParams: IECKeyGenerationParameters;

  KeyPair: IAsymmetricCipherKeyPair;
  privParams: IECPrivateKeyParameters;
  pubParams: IECPublicKeyParameters;

  agreement: IBasicAgreement;
  bigInteger: TBigInteger;

  serverprivkey: IECPrivateKeyParameters;
  SharedSecret: TBigInteger;
begin
  try
    FCurve :=  TCustomNamedCurves.GetByName('secp256k1');
    FRandom := TSecureRandom.Create();

    domain := TECDomainParameters.Create(FCurve.Curve, FCurve.G, FCurve.N, FCurve.H, FCurve.GetSeed);
    generator := TECKeyPairGenerator.Create('ECDSA');
    keygenParams := TECKeyGenerationParameters.Create(domain, FRandom);
    generator.Init(keygenParams);

    KeyPair := generator.GenerateKeyPair();
    privParams := KeyPair.Private as IECPrivateKeyParameters;
    pubParams := KeyPair.Public as IECPublicKeyParameters;

    Memo.Lines.Add('Private Key: ' + UpperCase(privParams.D.ToString(16)));
    Memo.Lines.Add('Public Key: ' + BytesToString(pubParams.Q.Normalize.GetEncoded));

    agreement := TECDHBasicAgreement.Create();

    bigInteger := TBigInteger.Create(THex.Decode(SERVER_PRIVATE_KEY));
    Memo.Lines.Add('Server Private Key: ' + BytesToString(bigInteger.ToByteArray));
    //Memo.Lines.Add('Server Private Key: ' + bigInteger.ToString);

    serverprivkey := TECPrivateKeyParameters.Create('ECDSA', bigInteger, domain); //Here gets the error


    agreement.Init(privParams);
    SharedSecret := agreement.CalculateAgreement(serverprivkey);

    Memo.Lines.Add('Shared Secret: ' + THex.Encode(SharedSecret.ToByteArray, true));
  except on E: Exception do
    ShowMessage(e.ToString);
  end;
end;

Can someboby help me?

Thank you.

I can't find aes/gcm/nopadding ? I searched whole internet and can;t find anything.

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Access violation in rtl270.bpl

Description
Hi, after struggling a little to build the crypto, hash and simplebase libraries i tried to code some AES encryption to see if it works as expected, but while trying i got stuck, the application compiles successfully but an error is raised when i try to execute the first library call, TAesEngine.Create(), that leads me to believe i'm either not compiling my application correctly on Rad studio, some settings might be wrong, or the compiled library has a problem.

To Reproduce
Compiled the libraries on Rad Studio 10.4, computer is running Windows 10.
Compiled SimpleBaseLib4Pascal, HashLib4Pascal and CryptoLib4Pascal for release, win64 configuration.

Output paths:
C:\Users\Public\Documents\Embarcadero\Studio\21.0\Bpl\Win64
C:\Users\Public\Documents\Embarcadero\Studio\21.0\Dcp\Win64

The *Bpl* path is on the system Path env var.

The Dcp's are included on the project via the Project>Options>Runtime Packages menu under All configurations, Link with Runtime Packages is true, Runtime packages contains the packages names. On the little folder icon we can see a dialogue with the option Search path, it also contains both the Dcp and Bpl output paths.

Auto completion can see the symbols on the IDE editor, compiling works nicely, then i make the call:

Crypto.pas:

unit Crypto;

interface

uses
    System.SysUtils,
    ClpAesEngine,
    ClpIAesEngine,
    ClpIBlockCipher,
    ClpIBufferedCipher,
    ClpIBufferedBlockCipher,
    ClpBufferedBlockCipher,
    ClpIKeyParameter,
    ClpParameterUtilities,
    ClpConverters,
    ClpICipherParameters
;

function en(input : String; key : String) : String;

implementation

function en(input : String; key : String) : String;
var
    engine : TAesEngine;
    blockCipher: IBlockCipher;
    cipher: IBufferedCipher;
    keyParameter : IKeyParameter;
    keyBytes : TBytes;
    res : TBytes;
begin
    engine.Create();
    blockCipher := engine as IBlockCipher; // ECB
    cipher := TBufferedBlockCipher.Create(blockCipher) as IBufferedCipher;

    keyBytes := TConverters.ConvertHexStringToBytes(key);
    keyParameter := TParameterUtilities.CreateKeyParameter('AES', keyBytes);

    cipher.Init(true, keyParameter as ICipherParameters);
    res := cipher.DoFinal(TConverters.ConvertHexStringToBytes(input));

    result := TConverters.ConvertBytesToHexString(res, true);
end;

end.

Behavior
When i make the call to engine.Create(), first line of the function en(), the programs raises a dialogue of access violation that reads:

Access violation at address 00000000012C7ABE in module 'rtl270.bpl'. Read of address FFFFFFFFFFFFFFFF.

Call stack when trying to call engine.Create():

rtl.System._AfterConstruction($4882A58)
rtl.System.TObject.Create
Cry.en('SYSDBA','773AEF0B12812B2B3A13761CBE167A86')
modal_db.Tmodal_db_form.alterClick(???)
vcl.Vcl.Controls.TControl.Click
vcl.Vcl.StdCtrls.TCustomButton.Click
vcl.Vcl.StdCtrls.TCustomButton.CNCommand(???)
rtl.System.TObject.Dispatch((no value))
vcl.Vcl.Controls.TControl.WndProc($14E3D0)
vcl.Vcl.Controls.TWinControl.WndProc($14E3D0)
vcl.Vcl.StdCtrls.TButtonControl.WndProc($14E3D0)
vcl.Vcl.Controls.TControl.Perform(???,???,???)
vcl.Vcl.Controls.DoControlMsg(???,(no value))
vcl.Vcl.Controls.TWinControl.WMCommand($14E8C0)
vcl.Vcl.Forms.TCustomForm.WMCommand($14E8C0)
rtl.System.TObject.Dispatch((no value))
vcl.Vcl.Controls.TControl.WndProc($14E8C0)
vcl.Vcl.Controls.TWinControl.WndProc($14E8C0)
vcl.Vcl.Forms.TCustomForm.WndProc($14E8C0)
vcl.Vcl.Controls.TWinControl.MainWndProc($14E8C0)
rtl.System.Classes.StdWndProc(???,???,???,???)
:00007FFEDD73E858 ; C:\Windows\System32\user32.dll
:00007FFEDD73DE1B ; C:\Windows\System32\user32.dll
:00007FFEDD73D68A ; C:\Windows\System32\user32.dll
:00007FFEC4FB2467 ; C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.19041.1110_none_60b5254171f9507e\comctl32.dll
:00007FFEC4FC20F0 ; C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.19041.1110_none_60b5254171f9507e\comctl32.dll
:00007FFEDD73E858 ; C:\Windows\System32\user32.dll
:00007FFEDD73E4EE ; C:\Windows\System32\user32.dll
vcl.Vcl.Controls.TWinControl.DefaultHandler((no value))
vcl.Vcl.Controls.TControl.WMLButtonUp($111)
rtl.System.TObject.Dispatch((no value))
vcl.Vcl.Controls.TControl.WndProc($14F2D0)
vcl.Vcl.Controls.TWinControl.WndProc($14F2D0)
vcl.Vcl.StdCtrls.TButtonControl.WndProc($14F2D0)
vcl.Vcl.Controls.TWinControl.MainWndProc($14F2D0)
rtl.System.Classes.StdWndProc(???,???,???,???)
:00007FFEDD73E858 ; C:\Windows\System32\user32.dll
:00007FFEDD73E299 ; C:\Windows\System32\user32.dll
vcl.Vcl.Forms.TApplication.ProcessMessage(nil)
vcl.Vcl.Forms.TApplication.HandleMessage
vcl.Vcl.Forms.TCustomForm.ShowModal
main.Tmain_form.config_dbClick(???)
vcl.Vcl.Menus.TMenuItem.Click
vcl.Vcl.Menus.TMenu.DispatchCommand(???)
vcl.Vcl.Forms.TCustomForm.WMCommand($14FB90)
rtl.System.TObject.Dispatch((no value))
vcl.Vcl.Controls.TControl.WndProc($14FB90)
vcl.Vcl.Controls.TWinControl.WndProc($14FB90)
vcl.Vcl.Forms.TCustomForm.WndProc($14FB90)
vcl.Vcl.Controls.TWinControl.MainWndProc($14FB90)
rtl.System.Classes.StdWndProc(???,???,???,???)
:00007FFEDD73E858 ; C:\Windows\System32\user32.dll
:00007FFEDD73E299 ; C:\Windows\System32\user32.dll
vcl.Vcl.Forms.TApplication.ProcessMessage(nil)
vcl.Vcl.Forms.TApplication.HandleMessage
vcl.Vcl.Forms.TApplication.Run
BloqDeBloq.BloqDeBloq
:00007FFEDEA07034 ; C:\Windows\System32\KERNEL32.DLL
:00007FFEDF602651 ; <UNKNOWN>

Additional context
All this is happening on a single form VCL application.

I tried copying the bpl files for the libs side by side with the application executable but it didn't work either.

I'm pretty sure that i missed something while compiling the Libs and or missing something on the application compile/linking as well, and that all this is a miss linked runtime package kinda deal.

Thanks for reading and sorry if i this might be a newbie and/or unrelated question. Best regards.

ClpEd25519Blake2B

Hi!

ClpEd25519Blake2B pas

I'm trying to compile ..\CryptoLib.Samples\Delphi.Samples\UsageSamples.dpr but can't do it without ClpEd25519Blake2B.pas:

ClpEd25519Blake2B

Where I can find it?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.