choey
choey

Reputation: 43

SHA256 Hash in Ruby not expected value

If I use OpenSSL to SHA256 hash the string hashthisstring123$

> echo -n "hashthisstring123$" | openssl dgst -sha256

I get this result:

> 052582d953f79d1e8502fdf063850888ee8426d3a5a6f46c1a0394d16056a51b

I have code to do this in Ruby, like this:

def self.test1
    str = "hashthisstring123$"
    retval = Digest::SHA256.hexdigest(str)
    return retval
end

It gives this (expected) result:

> Util.test1
=> "052582d953f79d1e8502fdf063850888ee8426d3a5a6f46c1a0394d16056a51b"

If I use OpenSSL to SHA256 hash the string 6nQ5t$hWGu8Kpassword123

> echo -n "6nQ5t$hWGu8Kpassword123" | openssl dgst -sha256

I get this result:

> 57cd553e7886a2c8eea92926e420d33d315418ffe6b98e5c34f1679607207d75

In Ruby, I have a method like this:

def self.test2
    str = "6nQ5t$hWGu8Kpassword123"
    retval = Digest::SHA256.hexdigest(str)
    return retval
end

And it gives this (unexpected) result:

> Util.test2
=> "1924de3da90f631c0943a47e4d4d80362d622e9656b5e2861f252a16bffb3d88"

What's going on here?

Upvotes: 2

Views: 284

Answers (1)

Siim Liiser
Siim Liiser

Reputation: 4348

Using a 3rd source (this for example) would tell you that the ruby version is correct. That means the issue is with your terminal/bash solution. Indeed, if we simplify it a bit we can see that there's something wrong.

> echo "6nQ5t$hWGu8Kpassword123"
6nQ5t

$ is a special symbol and will need to be escaped.

> echo "6nQ5t\$hWGu8Kpassword123"
6nQ5t$hWGu8Kpassword123
> echo -n "6nQ5t\$hWGu8Kpassword123" | openssl dgst -sha256
1924de3da90f631c0943a47e4d4d80362d622e9656b5e2861f252a16bffb3d88

Upvotes: 3

Related Questions