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" 
Share:
90,717

Related videos on Youtube

quackingduck
Author by

quackingduck

Updated on November 07, 2020

Comments

  • quackingduck
    quackingduck over 3 years
    • Jonas Elfström
      Jonas Elfström over 7 years
      SHA-1 is has been shown to be insecure. Consider using safer alternatives, such as SHA-256, or SHA-3. shattered.io
  • oligan
    oligan about 13 years
    Isn't this a duplicate of @devstopfix's answer?
  • Rixius
    Rixius about 13 years
    even 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
    Davidslv about 13 years
    Don'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
    andrewrk over 12 years
    There's also Digest::SHA1.base64digest 'foo'
  • andrewrk
    andrewrk over 12 years
    FYI, the 'hmac-sha1' requirement is met from the gem 'ruby-hmac'
  • jwfearn
    jwfearn about 12 years
    FYI: 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
    Blixxy almost 12 years
    what'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
    Gus Shortz about 11 years
    Need require 'digest/sha1' in order to use SHA1 method.
  • Joshua Pinter
    Joshua Pinter almost 4 years
    FYI, you should use Digest::SHA2.hexdigest now as it is more secure and has not (yet) been found to have any collisions.