8

我正在尝试从ankoder.com测试 API,并且在身份验证令牌的摘要计算上遇到问题。当我尝试从 C# 调用时,示例是 ruby​​。当我比较 HMAC-SHA1 中的摘要结果时,我遇到了密钥结果的问题。

为了方便测试,代码如下:

require 'hmac-sha1'
require 'digest/sha1'
require 'base64'
token="-Sat, 14 Nov 2009 09:47:53 GMT-GET-/video.xml-"
private_key="whatever"
salt=Digest::SHA1.hexdigest(token)[0..19]
passkey=Base64.encode64(HMAC::SHA1.digest(private_key, salt)).strip

这给了我结果:“X/0EngsTYf7L8e7LvoihTMLetlM=\n”如果我在 C# 中尝试以下内容:

const string PrivateKey = "whatever";

var date = "Sat, 14 Nov 2009 09:47:53 GMT";//DateTime.Now.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
string token=string.Format("-{0}-GET-/video.xml-", date);

var salt_binary=SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(token));
var salt_hex=BitConverter.ToString(salt_binary).Replace("-", "").ToLower();
var salt =salt_hex.Substring(0,20);

var hmac_sha1 =
            new HMACSHA1(Encoding.ASCII.GetBytes(salt));
hmac_sha1.Initialize();

var private_key_binary = Encoding.ASCII.GetBytes(PrivateKey);
var passkey_binary = hmac_sha1.ComputeHash(private_key_binary,0,private_key_binary.Length);

var passkey = Convert.ToBase64String(passkey_binary).Trim();

salt 结果是一样的,但是密码结果是不同的——C# 给了我:

QLC68XjQlEBurwbVwr7euUfHW/k=

两者都生成盐:f5cab5092f9271d43d2e

知道发生了什么吗?

4

2 回答 2

11

您在 C# 代码中放置PrivateKeysalt错误的位置;根据您的 Ruby 代码,PrivateKey它是 HMAC 的密钥。

另请注意,您在 Ruby 程序生成的哈希末尾包含了一个换行符(无论如何,根据您的示例输出)。您不能包含换行符,否则哈希将不匹配。

这个 C# 程序纠正了第一个问题:

using System;
using System.Security.Cryptography;
using System.Text;

namespace Hasher
{
  class Program
  {
    static void Main(string[] args)
    {
      const string PrivateKey = "whatever";

      string date = "Sat, 14 Nov 2009 09:47:53 GMT";
      string token = string.Format("-{0}-GET-/video.xml-", date);

      byte[] salt_binary = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(token));
      string salt_hex = BitConverter.ToString(salt_binary).Replace("-", "").ToLower();
      string salt = salt_hex.Substring(0, 20);

      HMACSHA1 hmac_sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(PrivateKey));
      hmac_sha1.Initialize();

      byte[] private_key_binary = Encoding.ASCII.GetBytes(salt);
      byte[] passkey_binary = hmac_sha1.ComputeHash(private_key_binary, 0, private_key_binary.Length);

      string passkey = Convert.ToBase64String(passkey_binary).Trim();
    }
  }
}
于 2009-11-14T12:10:25.680 回答
3

我看到2个问题,

  1. 你得到了键/数据反转。在 Ruby 中,private_key 是键,盐是数据。在 C# 中,您做了相反的事情。
  2. 如果您的任何字符串中允许使用非 ASCII,则必须确保使用相同的编码。Ruby 将所有内容都视为原始字节,因此 C# 必须匹配其编码。如果使用 jcode,C# 中的编码应该与 $KCODE 匹配。
于 2009-11-14T16:18:52.337 回答