Sha256: ffba6d8a61c6324f6df334eb70cd4f6b8d1c3ecf46c30f964dd5f2fe76a33587

Contents?: true

Size: 1.24 KB

Versions: 3

Compression:

Stored size: 1.24 KB

Contents

#
# A simple secret generator
#
# 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)
    HEX = (0..9).to_a + ('a'..'f').to_a

    #
    # generate a secret with with no ambiguous characters.
    #
    # +length+ is in chars
    #
    # 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.
    #
    def self.generate(length = 16)
      seed
      OpenSSL::Random.random_bytes(length).bytes.to_a.collect { |byte|
        CHARS[ byte % CHARS.length ]
      }.join
    end

    #
    # generates a hex secret, instead of an alphanumeric on.
    #
    # length is in bits
    #
    def self.generate_hex(length = 128)
      seed
      OpenSSL::Random.random_bytes(length/4).bytes.to_a.collect { |byte|
        HEX[ byte % HEX.length ]
      }.join
    end

    private

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

  end
end; end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
leap_cli-1.5.1 lib/leap_cli/util/secret.rb
leap_cli-1.5.0 lib/leap_cli/util/secret.rb
leap_cli-1.2.5 lib/leap_cli/util/secret.rb