如何使用DCPcrypt进行哈希?

时间:2015-03-17 18:15:51

标签: delphi hash cryptography sha1 delphi-xe5

我试图找到一个函数示例,如何使用Sha1和DCPcrypt散列文本。

我有以下示例。似乎总是弹出。 但它每次都会返回汉字。请协助核实该功能。

function TForm1.EncryptThis(aString : string) : string;
var
   Cipher: TDCP_cast256;
   KeyStr: string;
begin
   KeyStr:= '';
   Cipher:= TDCP_cast256.Create(Self);
   Cipher.InitStr(KeyStr,TDCP_sha1);
   result := Cipher.EncryptString(aString);
   Cipher.Burn;
   Cipher.Free;
end;

更新 使用下面的链接和信息,我构建了这些功能。但正如我所说,这对我来说并没有多大意义。所以请原谅无知。

但是代码不起作用。它的输出是3F3F3F3F3F3F3F3F3F3F00000000000000000000,而它应该是40bd001563085fc35165329ea1ff5c5ecbdbbeef,因为我告诉程序有123

请帮忙。

function CalcDigest(text: string): string;
var
  x: TDCP_hash;
begin
  x := TDCP_sha1.Create(nil);
  try
    x.Init;
    x.UpdateStr(text);
    SetLength(Result, x.GetHashSize div 8);
    x.Final(Result[1]);
  finally
    x.Free;
  end;
end;

function String2Hex(const Buffer: Ansistring): string;
begin
  SetLength(result, 2*Length(Buffer));
  BinToHex(@Buffer[1], PWideChar(@result[1]), Length(Buffer));
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
begin
  memo2.Lines.Add(String2Hex(CalcDigest(memo1.Lines.Strings[0])));
end;

2 个答案:

答案 0 :(得分:1)

this判断,您可以这样做:

function CalcDigest(text: string): string;
var
  x: TDCP_hash;
begin
  x := TDCP_sha1.Create(nil);
  try
    x.Init;
    x.UpdateStr(text);
    SetLength(Result, x.GetHashSize div 8);
    x.Final(Result[1]);
  finally
    x.Free;
  end;
end;

您可能希望在打印前对哈希进行编码,因为输出是二进制的。请参阅示例this question

答案 1 :(得分:1)

我对DCPCrypt不太熟悉。您也可以使用其他库。

1)Indy - 通常包含在Delphi中

function SHA1Text(const s: string): string;
begin
  with TIdHashSHA1.Create do
    try
      Result:=LowerCase(HashStringAsHex(s));
    finally
      Free;
    end;
end;
2)Wolfgang Ehrhardt的图书馆(据我所知最快)来自 http://www.wolfgang-ehrhardt.de/crchash_en.html

function SHA1Text(const s: string): string;
var
  Context: THashContext;
  SHA1Digest: TSHA1Digest;
begin
  SHA1Init(Context);
  SHA1Update(Context, pChar(s), length(s));
  SHA1Final(Context, SHA1Digest);

  Result:=HexStr(@SHA1Digest, SizeOf(SHA1Digest));
end;

注意:它来自Delphi 7.如果您使用unicode Delphi,则需要更新它。

相关问题