How do I create a SHA1 hash in ruby?
90,717
Solution 1
require 'digest/sha1'
Digest::SHA1.hexdigest 'foo'
Solution 2
For a Base64 encoded hash, to validated an Oauth signature, I used
require 'base64'
require 'hmac-sha1'
Base64.encode64((HMAC::SHA1.new('key') << 'base').digest).strip
Solution 3
I created a helper gem which is a simple wrapper around some sha1 code
require 'rickshaw'
> Rickshaw::SHA1.hash('LICENSE.txt')
=> "4659d94e7082a65ca39e7b6725094f08a413250a"
> "hello world".to_sha1
=> "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
Related videos on Youtube
Author by
quackingduck
Updated on November 07, 2020Comments
-
quackingduck over 3 years
-
Jonas Elfström over 7 yearsSHA-1 is has been shown to be insecure. Consider using safer alternatives, such as SHA-256, or SHA-3. shattered.io
-
-
oligan about 13 yearsIsn't this a duplicate of @devstopfix's answer?
-
Rixius about 13 yearseven if it is, it's some pretty ugly ruby code to be suggesting, and doesn't even mention that it needs `require \'digest/sha1\'' -1
-
Davidslv about 13 yearsDon't forget that stackoverflow has too many visitors, why you don't show us the right way to do it? Less critics more code examples
-
andrewrk over 12 yearsThere's also
Digest::SHA1.base64digest 'foo'
-
andrewrk over 12 yearsFYI, the 'hmac-sha1' requirement is met from the gem 'ruby-hmac'
-
jwfearn about 12 yearsFYI:
Digest
is part of the Ruby Standard Library (ruby-doc.org/stdlib-1.9.2/libdoc/digest/rdoc/index.html). It includes implementations for SHA1, SHA2, MD5 and others hash algorithms. -
Blixxy almost 12 yearswhat's this 'serialize' function? that's not a part of ruby. Worse yet, the string being passed to hexdigest isn't dynamic at all! This method would return the same hash regardless what data you give it!
-
Gus Shortz about 11 yearsNeed
require 'digest/sha1'
in order to useSHA1
method. -
Joshua Pinter almost 4 yearsFYI, you should use
Digest::SHA2.hexdigest
now as it is more secure and has not (yet) been found to have any collisions.