我需要为Amazon web服务API生成HMAC-SHA256签名。旧的DCPcrypt库有sha256例程,但不做HMAC签名。有没有人知道我可以使用的免费散列库?
发布于 2010-01-06 05:23:13
经过更多的搜索,我发现了OpenStreamSec -它看起来几年前就被废弃了,但仍然可以用D2007编译。
http://sourceforge.net/projects/openstrsecii/
为Amazon生成HMAC-256非常简单:
StrToMime64(HMACString(haSHA256, SecretKey, 32, DataToHash));发布于 2016-10-22 01:43:25
Delphi附带安装了Indy,并且Indy有一个TIdHMACSHA256类:
uses
IdGlobal, IdHashSHA, IdHMAC, IdHMACSHA1, IdSSLOpenSSL;
function CalculateHMACSHA256(const value, salt: String): String;
var
hmac: TIdHMACSHA256;
hash: TIdBytes;
begin
LoadOpenSSLLibrary;
if not TIdHashSHA256.IsAvailable then
raise Exception.Create('SHA256 hashing is not available!');
hmac := TIdHMACSHA256.Create;
try
hmac.Key := IndyTextEncoding_UTF8.GetBytes(salt);
hash := hmac.HashValue(IndyTextEncoding_UTF8.GetBytes(value));
Result := ToHex(hash);
finally
hmac.Free;
end;
end;发布于 2010-01-05 20:26:50
我最喜欢的答案是--我会使用OpenSSL库,HMAC函数。通过采用和改编M Ferrante http://www.disi.unige.it/person/FerranteM/delphiopenssl/的工作,我已经成功地使用了Delphi语言中的OpenSSL库
有关其他OpenSSL签名等信息,请参阅this link
在D2010中是这样的(libeay32是取自网站的单位,并针对unicode/D2010进行了稍微修改):
uses libeay32;
const
LIBEAY_DLL_NAME = 'libeay32.dll';
EVP_MAX_MD_SIZE = 64;
function EVP_sha256: pEVP_MD; cdecl; external LIBEAY_DLL_NAME;
function HMAC(evp: pEVP_MD; key: PByte; key_len: integer;
data: PByte; data_len: integer;
md: PByte; var md_len: integer): PByte; cdecl; external LIBEAY_DLL_NAME;
function GetHMAC(const AKey, AData: string): TBytes;
var
key, data: TBytes;
md_len: integer;
res: PByte;
begin
OpenSSL_add_all_algorithms;
// Seed the pseudo-random number generator
// This should be something a little more "random"!
RAND_load_file('c:\windows\paint.exe', 512);
key := TEncoding.UTF8.GetBytes(AKey);
data := TEncoding.UTF8.GetBytes(AData);
md_len := EVP_MAX_MD_SIZE;
SetLength(result, md_len);
res := HMAC(EVP_sha256, @key[0], Length(key), @data[0], Length(data), @result[0], md_len);
if (res <> nil) then
begin
SetLength(result, md_len);
end;
end;然后使用关键短语和数据字符串调用它。结果是一个TBytes,它可以根据需要转换为Base64,例如使用类似JclMime或简单的HexToString类型函数。
对于较旧版本的Delphi,您必须将PBytes更改为PChars或类似的东西。
免责声明:我没有参考数据来测试它,但它似乎工作得很好!
https://stackoverflow.com/questions/2003194
复制相似问题