Skip to content

Instantly share code, notes, and snippets.

@tlossen
Created December 10, 2009 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlossen/253234 to your computer and use it in GitHub Desktop.
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
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