Created
January 9, 2011 19:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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