简体   繁体   English

C#到Ruby sha1 base64编码

[英]C# to Ruby sha1 base64 encode

I'm trying to replicate the Convert.ToBase64String() behavior in Ruby. 我正在尝试在Ruby中复制Convert.ToBase64String()行为。

Here is my C# code: 这是我的C#代码:

var sha1 = new SHA1CryptoServiceProvider();
var passwordBytes = Encoding.UTF8.GetBytes("password");
var passwordHash = sha1.ComputeHash(passwordBytes);
return Convert.ToBase64String(passwordHash); // returns "W6ph5Mm5Pz8GgiULbPgzG37mj9g="

When I try the same thing in Ruby, I get a different base64 string for the same sha1 hash: 当我在Ruby中尝试相同的事情时,我得到一个不同的base64字符串用于相同的sha1哈希:

require 'digest/sha1'
require 'base64'
sha1 = Digest::SHA1.hexdigest('password')
# sha1 = 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
base64 = Base64.strict_encode64(sha1)
# base64 = "NWJhYTYxZTRjOWI5M2YzZjA2ODIyNTBiNmNmODMzMWI3ZWU2OGZkOA=="

I verified in the debugger that the C# passwordBytes byte array matches the sha1 value in the Ruby example. 我在调试器中验证了C# passwordBytes字节数组与Ruby示例中的sha1值匹配。 Is there a special way I need to use Base64 in Ruby to get the same string that the C# code produces? 有没有一种特殊的方法我需要在Ruby中使用Base64来获得C#代码生成的相同字符串?

You're base64-encoding the string "5baa61..." , not "\\x5b\\xaa\\x61..." 你是base64编码字符串"5baa61..." ,而不是"\\x5b\\xaa\\x61..."

Change hexdigest to digest : hexdigest更改为digest

sha1 = Digest::SHA1.digest('password')
base64 = Base64.strict_encode64(sha1)

Your C# and Ruby code are doing slightly different things. 你的C#和Ruby代码做的事情略有不同。 In your C# code, passwordHash is a byte[20]. 在你的C#代码中,passwordHash是一个字节[20]。 In your Ruby code, sha1 contains a 40-character string. 在您的Ruby代码中,sha1包含一个40个字符的字符串。 So you're Base64 encoding two different things. 所以你是Base64编码两个不同的东西。 Hence the different results. 因此结果不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM