Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Refactor IdGenerator

Before using SecureRandom, do a quick test whether it returns "random"
strings.
  • Loading branch information...
commit 966a6affd3bbfde9a0f3c8f69780a78bdd24a85c 1 parent 5075a89
Michael Neumann authored
Showing with 16 additions and 5 deletions.
  1. +16 −5 lib/wee/id_generator.rb
21 lib/wee/id_generator.rb
View
@@ -38,8 +38,22 @@ class IdGenerator::Secure < IdGenerator
def initialize(salt='wee')
@salt = salt
+
+ @use_secure = false
+ if defined?(::SecureRandom)
+ begin
+ @use_secure = true if next_secure != next_secure
+ rescue NotImplementedError
+ end
+ end
+ end
+
+ def next
+ pack(@use_secure ? next_secure : next_md5)
end
+ protected
+
def next_md5
now = Time.now
dig = Digest::MD5.new
@@ -50,15 +64,12 @@ def next_md5
dig.update(@salt.to_s)
dig.digest
end
-
+
def next_secure
SecureRandom.random_bytes(16)
- rescue NotImplementedError
- next_md5
end
- def next
- str = defined?(::SecureRandom) ? next_secure : next_md5
+ def pack(str)
packed = [str].pack('m')
packed.tr!("=\r\n", '')
packed.tr!('+/', '-_')
Please sign in to comment.
Something went wrong with that request. Please try again.