C # for Ruby sha1 base64 encode

I am trying to replicate 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 to do the same 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 checked in the debugger that the C # byte array passwordBytesmatches the value sha1in the Ruby example. Is there a special way that I need to use Base64 in Ruby to get the same line as C # code?

+5
source share
2 answers

You are encoding a base64 string "5baa61...", not"\x5b\xaa\x61..."

Change hexdigestto digest:

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

# Ruby . # Hash [20]. Ruby- sha1 40- . , Base64 . .

+2

All Articles