【发布时间】:2016-11-30 18:36:38
【问题描述】:
我在 VCL 应用程序中使用外部 DLL 来计算 HMAC sha256 哈希,https://www.chilkatsoft.com/delphiDll.asp,我需要一种在 Delphi 10 中为 Android 执行此操作的方法,我在 delphi 中找不到任何适用于 android 的方法, 这是使用 DLL 执行此操作的代码
function TForm2.HMAC(const s: pwidechar): string;
var
crypt: HCkCrypt2;
success: Boolean;
mac: PWideChar;
begin
crypt := CkCrypt2_Create();
// Any string argument automatically begins the 30-day trial.
success := CkCrypt2_UnlockComponent(crypt,'Anything for 30-day trial.');
if (success <> True) then
begin
Exit;
end;
// The output will be Hex, so set the EncodingMode:
CkCrypt2_putEncodingMode(crypt,'hex');
// Set the hash algorithm:
// Choices are: md5, sha-1, sha256, sha384, sha512, md2, haval
CkCrypt2_putHashAlgorithm(crypt,'sha256');
// Set the HMAC key:
CkCrypt2_SetHmacKeyEncoded(crypt,'my key','ascii');
mac := CkCrypt2__hmacStringENC(crypt,s);
Result := (mac);
CkCrypt2_Dispose(crypt);
end;
更新
我找到了一段代码来获取 HMAC SHA256..但我无法理解 它是如何工作的,就像上面的代码一样?
var
Hash: TIdHMACSHA256 ;
HashValue: TBytes;
begin
SetCurrentDir(ExtractFilePath(ParamStr(0)));
Hash := TIdHMACSHA256 .Create;
try
Hash.Key := TEncoding.ASCII.GetBytes('devaee2');
HashValue := Hash.HashValue(TFile.ReadAllBytes('menu.xml'));
// HashValue is an empty array, why?
Tag := Length(HashValue);
TFile.WriteAllBytes('menu.xml.hash', HashValue);
finally
FreeAndNil(Hash);
end;
end;
【问题讨论】:
-
Indy 通常在 Android 6 上运行良好。只有 Indy 使用 OpenSSL 在 Android 6 上不起作用。但是,Indy 的 hash 和 HMAC 类不是直接具体依赖于 OpenSSL,但他们可以在 OpenSSL 可用时使用它。 Indy 的
IdFIPS单元有一堆函数指针,你可以指向任何你想要的哈希 API(IdSSLOpenSSLHeaders单元将它们指向 OpenSSL 函数)用于 Indy 本身没有实现的哈希(一些哈希,如 MD5 和 SHA1,是本机实现的)。 -
查看
TIdHMAC类,它看起来可能会跳过一些本机哈希实现,依赖于外部库。我得调查一下。 -
看起来只有
TIdHMACSHA1受到影响。当外部散列库不可用时,我已将其更新为现在使用 Indy 的本机 SHA-1 实现。TIdHMACMD5已经在使用 Indy 的原生 MD5 实现。 -
我可以用它来计算 HMAC SHA256 吗? @RemyLebeau
-
是的,但要注意。正如您所发现的,Indy 有一个
TIdHMACSHA256类,它在内部使用TIdHashSHA256。但是 Indy 目前没有自己的 SHA-256 实现,所以TIdHashSHA256需要将一个外部库分配给IdFIPS单元中的 SHA-256 函数指针。没有它,哈希就会失败,这就是你的输出为空的原因(昨晚I made an update 所以TIdHMACSHA...类将引发异常)。如果您分配一个 SHA-256 库供 Indy 使用,那么TIdHMACSHA256将起作用。
标签: android delphi hash firemonkey delphi-10-seattle