Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# to Ruby sha1 base64 encode

I'm trying to replicate the Convert.ToBase64String() behavior in Ruby.

Here is my C# code:

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:

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. Is there a special way I need to use Base64 in Ruby to get the same string that the C# code produces?

like image 245
Mark Richman Avatar asked Nov 17 '10 22:11

Mark Richman


2 Answers

You're base64-encoding the string "5baa61...", not "\x5b\xaa\x61..."

Change hexdigest to digest:

sha1 = Digest::SHA1.digest('password')
base64 = Base64.strict_encode64(sha1)
like image 65
dtb Avatar answered Sep 30 '22 00:09

dtb


Your C# and Ruby code are doing slightly different things. In your C# code, passwordHash is a byte[20]. In your Ruby code, sha1 contains a 40-character string. So you're Base64 encoding two different things. Hence the different results.

like image 33
James Kovacs Avatar answered Sep 30 '22 02:09

James Kovacs