ruby中的hmac-sha1与C#HMACSHA1不同

Wil*_*ung 8 c# ruby hash sha1 hmac

我正在尝试从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
Run Code Online (Sandbox Code Playgroud)

这给了我结果:"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();
Run Code Online (Sandbox Code Playgroud)

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

QLC68XjQlEBurwbVwr7euUfHW/K =

两者都产生盐:f5cab5092f9271d43d2e

有什么好主意发生了什么?

Eme*_*gul 10

你已经把PrivateKeysalt在你的C#代码错误的位置; 根据您的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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)