簡體   English   中英

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

[英]hmac-sha1 in ruby differs from C# HMACSHA1

我正在嘗試從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

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

您已將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();
    }
  }
}

我看到2個問題,

  1. 你的關鍵/數據被逆轉了。 在Ruby中,private_key是關鍵,salt是數據。 在C#中,你做了相反的事情。
  2. 如果您的任何字符串中都允許使用非ASCII,則必須確保使用相同的編碼。 Ruby將所有內容都視為原始字節,因此C#必須與其編碼相匹配。 如果使用jcode,則C#中的編碼應與$ KCODE匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM