Created
December 10, 2009 09:25
-
-
Save tlossen/253234 to your computer and use it in GitHub Desktop.
how to generate a unique id which can be validated to be authentic
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 'digest' | |
module Id | |
SECRET = 'nobody knows the trouble' | |
def self.generate | |
a = digest("#{Time.now.to_f}:#{rand}") | |
b = digest(SECRET + a) | |
id = a + b | |
end | |
def self.valid?(id) | |
return false if id.nil? or id.length != 80 | |
a, b = id[0,40], id[40,40] | |
b == digest(SECRET + a) | |
end | |
private | |
def self.digest(text) | |
Digest::SHA1.hexdigest(text) | |
end | |
end | |
id = Id.generate | |
puts "#{Id.valid?(id)}: #{id}" | |
fake_id = id.reverse | |
puts "#{Id.valid?(fake_id)}: #{fake_id}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment