gpt4 book ai didi

delphi - Indy HMAC-SHA1 生成意外值

转载 作者:行者123 更新时间:2023-12-03 15:48:37 32 4
gpt4 key购买 nike

我正在尝试使用使用 OAuth 1.0a 并需要 HMAC-SHA1 进行签名的第三方服务。我用 C# 编写了一个工作版本,并尝试将其转移到 Delphi XE2。我立即注意到出了问题,服务器拒绝我的调用,说我的“签名无效”。这是我生成签名的方法:

function TOAuth1.GenerateSignature(signatureBase, key : string) : string;
var
hmacSha1 : TIdHMACSHA1;
keyBytes, textBytes, hashedBytes : TBytes;
begin
if(AnsiCompareText(fSignMethod,'PLAINTEXT') = 0) then
begin
Result := key;
end
else if(AnsiCompareText(fSignMethod,'HMAC-SHA1') = 0) then
begin
hmacSha1 := TIdHMACSHA1.Create;
SetLength(keyBytes,Length(key));
Move(key[1],keyBytes[0],Length(key));
hmacSha1.Key := keyBytes;
SetLength(textBytes,Length(signatureBase));
Move(signatureBase[1],textBytes[0],Length(signatureBase));
hashedBytes := hmacSha1.HashValue(textBytes);
Result := EncodeBase64(hashedBytes,Length(hashedBytes));
keyBytes := nil;
textBytes := nil;
hashedBytes := nil;

hmacSha1.Free;
hmacSha1 := nil;
end;
end;

我无法发现任何对我来说不对劲的地方,因此我从 C# 测试中获取了 signatureBasekey

signatureBase:POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Fsign-in-with-twitter%252F%26oauth_consumer_key%3DcChZNFj6T5R0TigYB9yd1w%2 6oauth_nonce%3Dea9ec8429b68d6b77cd5600adbbb0456% 26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318467427%26oauth_version%3D1.0

键:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg&

在 C# 中使用这些值,我得到了签名 F1Li3tvehgcraF8DMJ7OyxO4w9Y=,这是 Twitter 给我的预期值。但是,在 Delphi 中,我得到了签名 /kov410nJhE6PTlk0R8bjP7JQq4=

在 Delphi 中,我这样调用我的函数:

  signature := self.GenerateSignature('POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Fsign-in-with-twitter%252F%26oauth_consumer_key%3DcChZNFj6T5R0TigYB9yd1w%26oauth_nonce%3Dea9ec8429b68d6b77cd5600adbbb0456%26oauth_signature_method'+'%3DHMAC-SHA1%26oauth_timestamp%3D1318467427%26oauth_version%3D1.0','L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg&');
assert(AnsiCompareStr(signature,'F1Li3tvehgcraF8DMJ7OyxO4w9Y=') = 0,'Signature generated is invalid');

所以我的问题是:我是否错误地使用了 HMAC-SHA1?如果是这样,我应该采取什么措施来修复它?如果不是,那么 Indy 中 HMAC-SHA1 的实现是否错误?如果是这样,是否有一个易于使用(最好是免费)的单元可以正确处理它?还是这里还有其他完全错误的地方?

最佳答案

看起来像常见的 Unicode 字符串误解。自 Delphi 2009 起,string 映射到使用 UTF-16 编码的 UnicodeString,而不再映射到 AnsiString。所以,

Move(key[1],keyBytes[0],Length(key));

可能只会复制字符串的前半部分,每个字符 2 个字节。使用UTF8Encode首先将 key 转换为 UTF8,然后将其复制到 keyBytes 中。

关于delphi - Indy HMAC-SHA1 生成意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12484064/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com