Hashing a String With Delphi Encryption Compendium(DEC) » Developer.Team

Hashing a String With Delphi Encryption Compendium(DEC)

Hashing a String With Delphi Encryption Compendium(DEC)
Hashing a String With Delphi Encryption Compendium(DEC)


Today, I wanted to use the Delphi Encryption Compendium(DEC) to hash a string. It is a little bit difficult to figure out how to use the components since they are poorly documented, but after a few minutes, I came up with this. At first, I tried to use the CalcBinary function, which allows you pass a string to it. It worked fine, but it is limited due to the fact that it would cast all input strings as an ansistring type. As a result, I switched to the CalcStream type to overcome this limitation. Here are two functions which you can use to calculate an MD5 hash for either a UnicodeString or AnsiString. These functions can be easily converted to a different hash type simply by changing the declaration and create type.

The available hash types are:
THash_MD2, THash_MD4, THash_MD5, THash_RipeMD128, THash_RipeMD160, THash_RipeMD256, THash_RipeMD320, THash_SHA, THash_SHA1, THash_SHA256, THash_SHA384, THash_SHA512, THash_Haval128, THash_Haval160, THash_Haval192, THash_Haval224, THash_Haval256, Thash_Tiger, THash_Panama, THash_Whirlpool, THash_Whirlpool1, THash_Square, THash_Snefru128, THash_Snefru256, and THash_Sapphire.

You can specify haval rounds like this: hash.rounds:=3; //(3,4,and 5 are valid round types.)

Uses DECHash, DECFmt; 


Function GetMD5_Unicode(input: UnicodeString):String;
var
val: tStringStream;
hash: tHash_MD5;
len: int64;
Begin
val:=tStringStream.Create;
len:=length(input)*2;
val.Write(input[1], len);
val.Seek(0, soFromBeginning);
hash:=tHash_MD5.Create();
hash.Init;
result:=string(hash.CalcStream(val, len, TFormat_HEX));
hash.Free;
val.Free;
End;


Function GetMD5_Ansi(input: AnsiString):String;
var
val: tStringStream;
hash: tHash_MD5;
len: int64;
Begin
val:=tStringStream.Create;
len:=length(input);
val.Write(input[1] ,len);
val.Seek(0, soFromBeginning);
hash:=tHash_MD5.Create();
hash.Init;
result:=string(hash.CalcStream(val, len, TFormat_HEX));
hash.Free;
val.Free;
End;


The Delphi Encryption Compendium(DEC) can be downloaded here:
https://github.com/winkelsdorf/DelphiEncryptionCompendium/releases