Class: MiscHacks::Password

Inherits:
Object
  • Object
show all
Defined in:
lib/mischacks/password.rb

Constant Summary collapse

SALT_SET =
'a'..'z', 'A'..'Z', '0'..'9', %w{ . / }].map(&:to_a).flatten

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(encrypted) ⇒ Password

Returns a new instance of Password.



35
36
37
38
39
40
# File 'lib/mischacks/password.rb', line 35

def initialize encrypted
  @salt, @encrypted = encrypted.scan(/\A(\$[^$]+\$[^$]+\$)(.+)\z/).first
  if @salt.nil? or @encrypted.nil?
    raise ArgumentError, "Failed to parse #{encrypted.inspect}", caller
  end
end

Class Method Details

.new_from_password(password) ⇒ Object



31
32
33
# File 'lib/mischacks/password.rb', line 31

def self.new_from_password password
  new password.crypt('$6$%s$' % random_salt)
end

.random_saltObject



26
27
28
29
# File 'lib/mischacks/password.rb', line 26

def self.random_salt
  length = 9 + RANDOM.exp(3)  # Up to 9+(2³−1)=16
  (0...length).map { SALT_SET[RANDOM.exp(6)] }.join
end

Instance Method Details

#==(other) ⇒ Object



46
47
48
# File 'lib/mischacks/password.rb', line 46

def == other
  to_s == other.to_s
end

#=~(password) ⇒ Object



42
43
44
# File 'lib/mischacks/password.rb', line 42

def =~ password
  to_s == password.crypt(@salt)
end

#inspectObject



54
55
56
# File 'lib/mischacks/password.rb', line 54

def inspect
  '#<%s: %s>' % [self.class, to_s.inspect]
end

#to_sObject



50
51
52
# File 'lib/mischacks/password.rb', line 50

def to_s
  [@salt, @encrypted].join
end