delphi 使用CnPack 组件包(CnVCL)加密控件实现RSA2 SHA256 2048位签名

procedure TFormRSA.RSASHA256SignAndVerify(const PrivateKeyFile, PublicKeyFile: string);
var
  PrivateKey: TCnRSAPrivateKey;
  PublicKey: TCnRSAPublicKey;
  Data, Signature: TBytes;
  DataStr: string;
  IsValid: Boolean;
begin
  // 初始化 RSA 密钥对象
  PrivateKey := TCnRSAPrivateKey.Create(True); // 使用 CRT 加速
  PublicKey := TCnRSAPublicKey.Create;
  try
    // 从本地文件加载私钥
    if not CnRSALoadKeysFromPem(PrivateKeyFile, PrivateKey, nil) then
    begin
      Memo1.Lines.Add(Format('Failed to load private key from file:%s ', [PrivateKeyFile]));
      Exit;
    end;
    Memo1.Lines.Add('Private key loaded successfully.');

    // 从本地文件加载公钥
    if not CnRSALoadPublicKeyFromPem(PublicKeyFile, PublicKey) then
    begin
      Writeln('Failed to load public key from file: ', PublicKeyFile);
      Exit;
    end;
    Memo1.Lines.Add('Public key loaded successfully.');

    // 要签名的数据
    DataStr := 'Hello, RSA-SHA256!';
    Data := TEncoding.UTF8.GetBytes(DataStr);

    // 使用私钥对数据进行 SHA256 签名
    Signature := CnRSASignBytes(Data, PrivateKey, rsdtSHA256);
    if Length(Signature) = 0 then
    begin
      Memo1.Lines.Add('Failed to sign data.');
      Exit;
    end;

    // 输出签名
    Memo1.Lines.Add('Signature length: '+IntToStr( Length(Signature)));
    try
     // Base64编码签名结果
  var   SignBase64 := TNetEncoding.Base64.EncodeBytesToString(Signature);

  Memo1.Lines.Add('Signature: '+ SignBase64 );
    except
      on E: Exception do
        Memo1.Lines.Add('Error in BytesToHex: '+ E.ClassName+ ': '+ E.Message);
    end;

    // 使用公钥验证签名
    IsValid := CnRSAVerifyBytes(Data, Signature, PublicKey, rsdtSHA256);
    if IsValid then
      Memo1.Lines.Add('Signature is valid.')
    else
      Memo1.Lines.Add('Signature is invalid.');
  finally
    PrivateKey.Free;
    PublicKey.Free;
  end;
end;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值