Delphi下的HMACSHA1编码及Base64转换

这个博客展示了如何在Delphi中创建一个API请求,包括获取时间戳、生成随机字符串、组合JSON、创建URL、使用HMAC-SHA1签名以及POST数据。代码示例详细解释了每个步骤,并且涉及到了HTTP请求、加密和JSON处理。
摘要由CSDN通过智能技术生成

unit jmu1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, sLabel, sEdit,
  Vcl.Buttons, sBitBtn, sMemo,sButton, sGroupBox,EncdDecd,IdHMACSHA1,IdGlobal,httpapp,msxml,IdSSLOpenSSL,IdHTTP,json,dateutils,strutils;

type
  TForm1 = class(TForm)
    sBitBtn1: TsBitBtn;
    sMemo1: TsMemo;
    sGroupBox1: TsGroupBox;
    sLabel4: TsLabel;
    sLabel5: TsLabel;
    sLabel6: TsLabel;
    sEdit7: TsEdit;
    sEdit8: TsEdit;
    sEdit9: TsEdit;
    procedure sBitBtn1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    function GetTimeStamp:String;
    function GetRndString(strlength:Integer):string;//获取随机长度的字符串
    function CreateURL:string;
    function StreamToBase64(AStream: TStream): string;
    function BytesToBase64(const bytes: TIdBytes): string;
    function PostData(url,data:string):string;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function Tform1.CreateURL:string;//创建提交的URL地址
//1、获取时间戳  2、获取随机字符串  3、组合json  4、组合src  5、签名 6、组合提交的URL 7、提交
var
  userkey,url,rstr,ts,sign,jsonstr,querystr,src:string;
  bs:Tidbytes;
begin
  rstr:=self.GetRndString(6);//随机字符串
  self.sMemo1.Lines.Add(rstr);
  ts:=self.GetTimeStamp;//时间戳
  self.sMemo1.Lines.Add(ts);
  querystr:='appid=100400116&nonce='+rstr+'&t='+ts;
  Self.sMemo1.Lines.Add(querystr);
  jsonstr:='{"age":'+self.sEdit7.Text+',"idcard":"'+self.sEdit8.Text+'","name":"'+self.sEdit9.Text+'"}';
  src:='/test?'+querystr+jsonstr;
  self.sMemo1.Lines.Add(src);
  userkey:='a2af648dbe90b1aea2882b3998f7af6d';
  with TIdHMACSHA1.Create() do
  try
    key:=ToBytes(userkey);
    bs:=HashValue(ToBytes(src,IndyTextEncoding_UTF8));
  finally
    free;
  end;
  sign:=httpencode(AnsiToUtf8(self.BytesToBase64(bs)));
  self.sMemo1.Lines.Add(sign);
  url:='https://****.com/test?appid=100400116&nonce='+rstr+'&sign='+sign+'&t='+ts;
  result:=url;
end;


function TForm1.GetTimeStamp:String;
var
  SysTime: TsystemTime;
  timen,time2:TDateTime;
  ss2,ss3:int64;
  str2:string;
begin
  GetLocalTime(SysTime);
  timen:= SystemTimeToDateTime(SysTime);
  time2 := EncodeDateTime( 1970, 1, 1, 0, 0, 0, 0 );
  ss2 := 28800000;
//  ss3 := MilliSecondsBetween( timen, time2 );//返回毫秒级数据
  ss3 := SecondsBetween( timen, time2 );
  ss3 :=ss3- ss2;
  result := IntToStr(ss3);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  randomize;
end;

function TForm1.GetRndString(strlength:Integer):string;//获取随机长度的字符串
var
  i:integer;
  jg,strlist:string;
begin
  jg:='';
  strlist:='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  for i:=1 to strlength do
    jg:=jg+strlist[Random(62)+1];
  result:=jg;
end;


function TForm1.StreamToBase64(AStream: TStream): string;
var
objSS: TStringStream;
begin
objSS := TStringStream.Create('');
try
EncodeStream(AStream, objSS); // Delphi unit EncdDecd的方法
Result := objSS.DataString;
finally
FreeAndNil(objSS);
end;
end;

function TForm1.BytesToBase64(const bytes: TIdBytes): string;
var
memoryStream: TMemoryStream;
begin
memoryStream := TMemoryStream.Create;
memoryStream.WriteBuffer(bytes[0], Length(bytes));
memoryStream.Seek(0, soFromBeginning);
Result := StreamToBase64(memoryStream);
memoryStream.Free;
end;

function TForm1.PostData(url,data:string):string;
var
  jsonstr:string;
  sresponse:string;
  jsontosend:TStringStream;
  http1:tidhttp;
begin
//1、获取时间戳  2、获取随机字符串  3、组合json  4、组合src  5、签名 6、组合提交的URL 7、提交
  jsontosend:=TStringStream.Create(data,TEncoding.UTF8);
  http1:=TIdHTTP.Create(nil);
  try
    HTTP1.Request.ContentType := 'application/json; charset=utf-8';
    HTTP1.Request.CharSet := 'utf-8';
    try
      sResponse := HTTP1.Post(url, JsonToSend);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    FreeAndNil(HTTP1);
    FreeAndNil(JsonToSend);
  end;
  result:=sresponse;
end;

procedure TForm1.sBitBtn1Click(Sender: TObject);
var
  url,jsonstr:string;
begin
  url:=self.CreateURL;
  jsonstr:='{"age":'+self.sEdit7.Text+',"idcard":"'+self.sEdit8.Text+'","name":"'+self.sEdit9.Text+'"}';
  self.sMemo1.Lines.Add(url);
  self.sMemo1.Lines.Add(jsonstr);
  Self.sMemo1.Lines.Add(self.PostData(url,jsonstr));
end;

end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锋回路转2022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值