3

我正在尝试使用使用 OAuth 1.0a 并需要 HMAC-SHA1 进行签名的第 3 方服务。我用 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# 测试中拿了一个signatureBaseandkey

签名库: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&

在 C# 中使用这些值,我得到了签名F1Li3tvehgcraF8DMJ7OyxO4w9Y=,这是 Twitter 给我的预期值。然而,在德尔福,我得到了签名/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 的实现是否不正确?如果是这样,是否有一个易于使用(最好是免费的)单元可以正确处理它?还是这里有其他完全错误的地方?

4

1 回答 1

6

看起来像是常见的 Unicode 字符串误解。自 Delphi 2009 以来,string映射到UnicodeStringUTF-16 编码,不再映射到AnsiString. 所以,

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

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

于 2012-09-18T20:10:07.383 回答