164

SHA Hash functions

quackingduck
  • 5,845
  • 5
  • 29
  • 22

4 Answers4

397
require 'digest/sha1'
Digest::SHA1.hexdigest 'foo'
devstopfix
  • 6,698
  • 4
  • 34
  • 32
  • 43
    There's also `Digest::SHA1.base64digest 'foo'` – andrewrk Jan 14 '12 at 01:31
  • 14
    FYI: `Digest` is part of the Ruby Standard Library (http://www.ruby-doc.org/stdlib-1.9.2/libdoc/digest/rdoc/index.html). It includes implementations for SHA1, SHA2, MD5 and others hash algorithms. – jwfearn Jun 11 '12 at 18:07
  • FYI, you should use `Digest::SHA2.hexdigest` now as it is more secure and has not (yet) been found to have any collisions. – Joshua Pinter Sep 18 '20 at 15:22
8

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
Thiago Ganzarolli
  • 1,161
  • 12
  • 17
7

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" 
Gregory Ostermayr
  • 1,123
  • 10
  • 17
-24

Where 'serialize' is some user function defined elsewhere.

 def generateKey(data)
    return Digest::SHA1.hexdigest ("#{serialize(data)}")
 end
Ashley Raiteri
  • 700
  • 8
  • 17
r4ccoon
  • 3,056
  • 4
  • 26
  • 32
  • Isn't this a duplicate of @devstopfix's answer? – Andrew Grimm May 11 '11 at 23:43
  • 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 – Rixius May 23 '11 at 18:20
  • 16
    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 – Davidslv Jun 22 '11 at 11:39
  • 1
    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! – Blixxy Jul 07 '12 at 10:10
  • 2
    Need `require 'digest/sha1'` in order to use `SHA1` method. – Gus Shortz May 16 '13 at 19:22