I am trying to use the SHA-256 encryption function, but with no success.
I need to get a hash of a string and a file. I'm using Delphi 10.1 Berlin, and Indy for Hash.
My code:
uses System.Classes, IdHashSha, System.SysUtils;
function GetHashF(_filename: string): string;
var
sha: TIdHashSHA256;
fs: TFileStream;
begin
if TIdHashSHA256.IsAvailable then
begin
sha:= TIdHashSHA256.Create;
try
fs:= TFileStream.Create(_filename, fmOpenRead);
try
Result:= sha.HashStreamAsHex(fs);
finally
sha.Free;
end;
finally
fs.Free;
end;
end;
function GetHashS(_string: string): string;
var
sha: TIdHashSHA256;
begin
if TIdHashSHA256.IsAvailable then
begin
sha:= TIdHashSHA256.Create;
try
Result:= sha.HashStringAsHex(_string);
finally
sha.Free;
end;
end;
end;
But whenever I do this, it returns a clean string ("") for both function.
I used the breakpoint to check if it is passing from IsAvaible
, and it is not.
What is going on?
At this time, Indy only implements a few hashing algorithms natively, but that does not include SHA-256 (I have created a ticket for that feature).
For algorithms not implemented natively, Indy allows you to hook in an external hashing implementation of your choosing to provide the actual hash functionality. You are seeing IsAvailable
return false because you have not done that hookup yet.
You can use any hash implementation you want, as long as you assign appropriate wrapper functions to the following callbacks in the IdFIPS
unit:
IsHashingIntfAvail
UpdateHashInst
FinalHashInst
And for SHA-256 specifically, also:
GetSHA256HashInst
IsSHA256HashIntfAvail
By default, Indy can use OpenSSL as a hashing library:
add the IdSSLOpenSSLHeaders
unit to your uses
clause
call IdSSLOpenSSLHeaders.Load()
at runtime
deploy the OpenSSL binaries with your app executable.
IdSSLOpenSSLHeaders.pas
hooks up relevant OpenSSL functions for the IdFIPS
callbacks.