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;