C# 在ruby中生成HMACSHA1

C# 在ruby中生成HMACSHA1,c#,ruby,hmacsha1,C#,Ruby,Hmacsha1,我有以下代码片段来生成C#中的HMACSHA1签名。下面的代码是什么 Encoding encoding = new UTF8Encoding(); HMACSHA1 hmac = new HMACSHA1(encoding.GetBytes(SecretKey.ToCharArray())); StringBuilder data = new StringBuilder(); data.Append(Access); data.Append(Id); data.Append(Entity)

我有以下代码片段来生成C#中的HMACSHA1签名。下面的代码是什么

Encoding encoding = new UTF8Encoding();
HMACSHA1 hmac = new HMACSHA1(encoding.GetBytes(SecretKey.ToCharArray()));

StringBuilder data = new StringBuilder();

data.Append(Access);
data.Append(Id);
data.Append(Entity);
data.Append(Username);

string signature Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(data.ToString().ToCharArray())));
现在我想把它翻译成ruby,比如:

Base64.encode64(OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha1'), secret_key, data)
但是,对于相同的输入,结果并不相等。他们在内部使用不同的散列算法吗


感谢

正如回复中所建议的,问题与编码有关,在生成HMAC SHA1哈希时不使用原始字节

HMAC SHA1在为消息和机密提供相同字节时应始终生成相同的哈希。不同的语言和库应该实现完全相同的算法。Ruby版本中密钥和数据的字符编码是什么(例如使用
put secret\u key.encoding
进行检查)?还有一个猜测是,您正在用Ruby编码
hexdigest
,但在C#中调用
ComputeHash
——如果后者输出原始字节,那么这两个调用并不相等。正确,这就是问题所在。在ruby上,我使用的是hexdigest,这不是C#所使用的。如果你有时间,这个答案会更好,如果它显示,使用几行代码,你如何判断错误(没有编码数据-由你没有显示的代码控制-没有人能回答这个问题),而且非常重要的是,正确的Ruby代码行是什么。