From 3dc72b17a167b1f56a585f50bc8d0705c1b69292 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Zurcher?= Date: Wed, 4 Jan 2012 14:15:40 +0100 Subject: session: add sid generators --- lib/zorglub/session.rb | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/lib/zorglub/session.rb b/lib/zorglub/session.rb index 583b142..157c786 100644 --- a/lib/zorglub/session.rb +++ b/lib/zorglub/session.rb @@ -74,6 +74,40 @@ module Zorglub @instance[idx] = v end # + def generate_sid + begin sid = sid_algorithm end while Session.kls.sid_exists? sid + sid + end + # + begin + require 'securerandom' + # Using SecureRandom, optional length. + # SecureRandom is available since Ruby 1.8.7. + # For Ruby versions earlier than that, you can require the uuidtools gem, + # which has a drop-in replacement for SecureRandom. + def sid_algorithm; SecureRandom.hex(Session.sid_length); end + rescue LoadError + require 'openssl' + # Using OpenSSL::Random for generation, this is comparable in performance + # with stdlib SecureRandom and also allows for optional length, it should + # have the same behaviour as the SecureRandom::hex method of the + # uuidtools gem. + def sid_algorithm + OpenSSL::Random.random_bytes(Session.sid_length / 2).unpack('H*')[0] + end + rescue LoadError + # Digest::SHA2::hexdigest produces a string of length 64, although + # collisions are not very likely, the entropy is still very low and + # length is not optional. + # + # Replacing it with OS-provided random data would take a lot of code and + # won't be as cross-platform as Ruby. + def sid_algorithm + entropy = [ srand, rand, Time.now.to_f, rand, $$, rand, object_id ] + Digest::SHA2.hexdigest(entropy.join) + end + end + # end # end -- cgit v1.1-2-g2b99