我用这个代码来尝试一下 我需要得到像这个网站这样的结果https://sha512.online/
use IdHash,IdHashSHA;
function TForm1.SHA512(const AString: string): string;
var LSHA512: TIdHashSHA512;
begin
LSHA512 := TIdHashSHA512.Create;
try
Result := LSHA512.HashStringAsHex(AString);
finally
LSHA512.Free;
end;
end;
但它在 LSHA512.HashStringAsHex 行引发了访问冲突错误。 谢谢你。
您没有检查以确保
TIdHashSHA512.IsAvailable
是 True
before 使用 TIdHashSHA512.HashStringAsHex()
,例如:
use
IdHash, IdHashSHA;
function TForm1.SHA512(const AString: string): string;
var
LSHA512: TIdHashSHA512;
begin
if TIdHashSHA512.IsAvailable then // <-- ADD THIS!
begin
LSHA512 := TIdHashSHA512.Create;
try
Result := LSHA512.HashStringAsHex(AString);
finally
LSHA512.Free;
end;
end
else begin
// SHA-512 is not hooked up for use!!
end;
end;
SHA-512(以及大多数其他加密算法)不是 Indy 内置的,因此
TIdHashSHA512.IsAvailable
默认返回 False
。要使其返回 True
,IsHashingIntfAvail
单元中的 IsSHA512HashIntfAvail
和 IdFIPS
函数指针需要连接到实际实现 SHA-512 的库/API,例如 OpenSSL(通过 IdSSLOpenSSLHeaders
单元)。 HashStringAsHex()
本身需要将相应的函数赋值给GetSHA512HashInst
、UpdateHashInst
和FinalHashInst
函数指针。
例如:
use
IdHash, IdHashSHA,
IdSSLOpenSSLHeaders; // <-- ADD THIS!
// And then deploy OpenSSL DLLs with your app...
function TForm1.SHA512(const AString: string): string;
var
LSHA512: TIdHashSHA512;
begin
IdSSLOpenSSLHeaders.Load;
if TIdHashSHA512.IsAvailable then
begin
LSHA512 := TIdHashSHA512.Create;
try
Result := LSHA512.HashStringAsHex(AString);
finally
LSHA512.Free;
end;
end
else begin
// SHA-512 is not hooked up for use!!
end;
end;
由于 Delphi 7 仅支持 Windows 开发,如果您不想依赖第三方库,Microsoft 的 Crypto API 在现代 Windows 版本上确实支持 SHA-512,因此您可以选择在代码中编写一些函数来调用Crypto API,然后将这些函数分配给
IdFIPS
函数指针,例如:
uses
IdFIPS;
function MyHashingIntfAvail: Boolean;
begin
Result := True;
end;
function MySHA512HashIntfAvail: Boolean;
begin
Result := True;
end;
function MyGetSHA512HashInst: TIdHashIntCtx;
begin
// initialize SHA-512 as needed
// return a context that refers to its hash...
// see CryptCreateHash()
Result := ...;
end;
procedure MyUpdateHashInst(ACtx: TIdHashIntCtx; const AIn: TIdBytes);
begin
// update the context's hash as needed...
// see CryptHashData()
end;
function MyFinalHashInst(ACtx: TIdHashIntCtx): TIdBytes;
begin
// finalize the context's hash, free the context,
// and return the final hash...
// see CryptDestroyHash()
end;
initialization
IdFIPS.IsHashingIntfAvail := @MyHashingIntfAvail;
IdFIPS.IsSHA512HashIntfAvail := @MySHA512HashIntfAvail;
IdFIPS.GetSHA512HashInst := @MyGetSHA512HashInst;
IdFIPS.UpdateHashInst := @MyUpdateHashInst;
IdFIPS.FinalHashInst := @MyFinalHashInst;