【问题标题】:Convert string in hash sha256在哈希 sha256 中转换字符串
【发布时间】:2021-11-19 22:34:56
【问题描述】:

我想使用 DCPCrypt 将字符串转换为 sha256 哈希。 表单包含输入字符串的编辑、转换字符串的按钮和显示输出 sha256 哈希的另一个编辑。 我写了这段代码:

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, DCPsha256, StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    DCP_sha256_1: TDCP_sha256;
    Edit1: TEdit;
    Edit2: TEdit;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { private declarations }
  public

    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

function getsha256(S: String): String;
var
    Hash: TDCP_sha256;
    Digest: array[0..31] of byte;  // sha256 produces a 256bit digest (32bytes)
    Source: string;
    i: integer;
    str1: string;
  begin
    Source:= S;  // here your string for get sha256

    if Source <> '' then
    begin
      Hash:= TDCP_sha256.Create(nil);  // create the hash
      Hash.Init;                        // initialize it
      Hash.UpdateStr(Source);
      Hash.Final(Digest);               // produce the digest
      str1:= '';
      for i:= 0 to 31 do
        str1:= str1 + IntToHex(Digest[i],2);
      //form1.Edit2.Text:= s;                   // display the digest in lower case
      Form1.Edit2.Text:=UpperCase(str1);         // display the digest in capital letter
    end;
  end;

procedure TForm1.Button1Click(Sender: TObject);
  begin
    getsha256(Edit1.Text);  // show the sha256 of string in edit1
end;
end.

它有效。问题是我收到了来自 lazarus 的警告和提示。

  • 警告:局部变量“Digest”似乎未初始化;
  • 警告:似乎没有设置函数结果。

【问题讨论】:

    标签: hash sha256 lazarus


    【解决方案1】:

    第一个警告是误报。编译器不知道Hash.Final()会填写Digest,而且你也没有事先自己初始化。对FillByte()(甚至FillDWord())的简单调用就足够了:

    FillByte(Digest, SizeOf(Digest), 0);
    //FillDWord(Digest, SizeOf(Digest) div 4, 0);
    

    不过,第二个警告是正确的。您的getsha256() 函数被声明为返回String,但您根本没有设置该函数的Result。你应该改变这一行:

    Form1.Edit2.Text:=UpperCase(str1);
    

    改为:

    Result:=UpperCase(str1);
    

    然后在TForm1.Button1Click()中,更改这一行:

    getsha256(Edit1.Text);
    

    改为:

    Edit2.Text:=getsha256(Edit1.Text);
    

    【讨论】:

    • 感谢您的好意。
    • 有没有办法用种子加密字符串?然后让我解密。
    • 哈希是一个单向值,它不是加密。 DCPCrypt 还有很多其他的加密/解密类。
    • 可以,但是没有手册可以学习。
    • @Wario 真的吗?它有可用的文档:github.com/StephenGenusa/DCPCrypt/tree/master/Docs,特别是查看有关密码和块密码的页面。还提供了一个encryption demo
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2020-06-05
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多