如何使用 Delphi 7创建SHA-512加密哈希算法?[副本]

e0bqpujr  于 2023-10-18  发布在  其他
关注(0)|答案(2)|浏览(229)

这个问题已经有答案了

TidHashSHA512.isavailable is false on Windows 10(1个答案)
21天前关闭。
我用这个代码来尝试它,我需要得到这样的网站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行引发了一个Access Violation错误。谢谢

lf3rwulv

lf3rwulv1#

您没有检查以确保TIdHashSHA512.IsAvailableTrue * 在 * 使用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。要使其返回TrueIdFIPS单元中的IsHashingIntfAvailIsSHA512HashIntfAvail函数指针需要连接到实际实现SHA-512的库/API,例如OpenSSL(通过IdSSLOpenSSLHeaders单元)。HashStringAsHex()本身需要将相应的函数分配给GetSHA512HashInstUpdateHashInstFinalHashInst函数指针。
举例来说:

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开发,如果你不想依赖第三方库,微软的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;

相关问题