Skip to content

Instantly share code, notes, and snippets.

@half-ogre
Created January 9, 2011 19:48
Show Gist options
  • Save half-ogre/771947 to your computer and use it in GitHub Desktop.
Save half-ogre/771947 to your computer and use it in GitHub Desktop.
Creating a hash in Ruby with a random salt using /dev/random
require 'base64'
require 'digest/sha2'
def create(text)
salt_bytes = random_salt
salted_hash_bytes = Digest::SHA256.digest(salt_bytes+text)
Base64::encode64(salt_bytes+salted_hash_bytes)
end
def verify(hash, text)
salted_hash_bytes = Base64::decode64(hash)
salt_bytes = salted_hash_bytes[0..7]
hash_bytes = salted_hash_bytes[8..39]
hash_bytes == Digest::SHA256.digest(salt_bytes+text)
end
def random_salt
random = File.new('/dev/random', 'r')
random.read(16) #discrard first 16 bytes
salt = random.read(8)
random.close
salt
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment