1

I have the following code written in delphi.

with TIdHashMessageDigest5.Create do begin
    st2.Position := 0;
    Digest := HashValue( st2 );
    SetLength( Hash, 16 );
    Move( Digest, Hash[1], 16);
    Free;
end;

I need to convert that to use SHA1 hash. I couldn't find SHA1 type in the library. Can anyone help? I have looked for help on the internet but couldn't find any.

MKK
  • 11
  • 1
  • 4

3 Answers3

4

See here:

https://sergworks.wordpress.com/2014/10/25/high-performance-hash-library/

SHA1 hashing in Delphi XE

https://sourceforge.net/projects/sha1implementat/

http://www.colorfultyping.com/generating-a-sha-1-checksum-for-a-given-class-type/

BTW, you didn't mention your Delphi version. If you are using a modern version (XE onwards), I suppose that its standard libraries should support SHA-1, MD5, etc.

You could do it like this:

uses IdHashSHA;

function SHA1FromString(const AString: string): string;
var
  SHA1: TIdHashSHA1;
begin
  SHA1 := TIdHashSHA1.Create;
  try
    Result := SHA1.HashStringAsHex(AString);
  finally
    SHA1.Free;
  end;
end;
Community
  • 1
  • 1
lospejos
  • 1,958
  • 3
  • 19
  • 33
0

You appear to be using Indy 9, which does not support SHA1. SHA1 (and a few other hashes, including several other SHAs) was added in Indy 10. The interface for TIdHash was also re-written in Indy 10. Amongst other changes, the HashValue() method was replaced with new Hash...() and Hash...AsHex() methods (HashString(AsHex), HashStream(AsHex), HashBytes(AsHex)), eg:

uses
  ..., IdHash, IdHashMessageDigest;

var
  Hash: TIdBytes;
begin
  with TIdHashMessageDigest5.Create do
  try
    st2.Position := 0;
    Hash := HashStream( st2 );
  finally
    Free;
  end;
  // use Hash as needed...
end;    

uses
  ..., IdHash, IdHashSHA;

var
  Hash: TIdBytes;
begin
  with TIdHashSHA1.Create do
  try
    st2.Position := 0;
    Hash := HashStream( st2 );
  finally
    Free;
  end;
  // use Hash as needed...
end;    
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
  • Hi Remy, Thanks for your time. I will use it and see how it works for me. I am using Delphi 2005. Can you suggest from where do I fetch IdGlobal.pas as the one I have generate lot of "Undeclared Identifier" errors? – MKK Aug 17 '16 at 11:51
  • @MKK such as? it is not enough to just get a newer IdGlobal.pas by itself, you need to get a newer ersion of the entire Indy library as a whole. – Remy Lebeau Aug 17 '16 at 14:58
0

Two more options:

http://www.spring4d.org

unit Spring.Cryptography.SHA;

TSHA1 = class(THashAlgorithmBase, ISHA1)

http://lockbox.seanbdurkin.id.au/HomePage

unit LbProc;
procedure StreamHashSHA1(var Digest : TSHA1Digest; AStream : TStream);
procedure FileHashSHA1(var Digest : TSHA1Digest; const AFileName : string);
Arioch 'The
  • 15,529
  • 33
  • 61