aboutsummaryrefslogtreecommitdiff
path: root/lib/leap_cli/util/secret.rb
blob: 691065f27d9d7e0f853852da71c521fc6f78f985 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#
# A simple alphanumeric secret generator, with no ambiguous characters.
#
# Only alphanumerics are allowed, in order to make these passwords work
# for REST url calls and to allow you to easily copy and paste them.
#
# Uses OpenSSL random number generator instead of Ruby's rand function
#

require 'openssl'

module LeapCli; module Util

  class Secret

    CHARS = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + "_".split(//u) - "io01lO".split(//u)

    def self.generate(length = 16)
      seed
      OpenSSL::Random.random_bytes(length).bytes.to_a.collect { |byte|
        CHARS[ byte % CHARS.length ]
      }.join
    end

    def self.seed
      @pid ||= 0
      pid = $$
      if @pid != pid
        now = Time.now
        OpenSSL::Random.seed( [now.to_i, @pid, pid].join )
        @pid = pid
      end
    end

  end

end; end