Delphi 将appid time nonce_str 利用Hmacsha1算法加密之后 再base64编码
1、利用D10 以上自带的IdHMACSHA1
var app_secret,sha1Value,base64Value:string;
signSrcString:string;
bs : TIdBytes;
begin
appid := 'jzrhvabb71qp5yo08y9d';
time := '1562143733608';
nonce_str :='ebrb7nt4v8';
signSrcString := appid +'&'+time+'&'+nonce_str;
app_secret :='b52a0705dbf479192465e77454e97eb';
// signSrcString:='jzrhvabb71qp5yo08y9d&1562143733608&ebrb7nt4v8';
with TIdHMACSHA1.Create() do
try
Key := ToBytes(app_secret);
// bs := HashValue(ToBytes('jzrhvabb71qp5yo08y9d&1562143733608&ebrb7nt4v8'));
bs := HashValue(ToBytes(signSrcString));
finally
Free;
end;
base64Value := BytesToBase64(bs);
end;
这里非常注意:appid,time,nonce_str:WideString; 拼接字符串必须使用widestring;
function 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 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;