1 package SL::Auth::Password;
11 my ($class, %params) = @_;
13 # PBKDF2::Tiny expects data to be in octets. Therefore we must
14 # encode everything we hand over (login, password) to UTF-8.
16 # This hash method uses a random hash and not just the user's login
17 # for its salt. This is due to the official recommendation that at
18 # least eight octets of random data should be used. Therefore we
19 # must store the salt together with the hashed password. The format
22 # {PBKDF2}salt-in-hex:hash-in-hex
26 if ((defined $params{stored_password}) && ($params{stored_password} =~ m/^\{PBKDF2\} ([0-9a-f]+) :/x)) {
27 $salt = (split m{:}, Encode::encode('utf-8', $1), 2)[0];
30 my @login = map { ord } split m{}, Encode::encode('utf-8', $params{login});
31 my @random = map { int(rand(256)) } (0..16);
33 $salt = join '', map { sprintf '%02x', $_ } @login, @random;
36 my $hashed = "{PBKDF2}${salt}:" . join('', map { sprintf '%02x', ord } split m{}, PBKDF2::Tiny::derive('SHA-256', $salt, Encode::encode('utf-8', $params{password})));
42 my ($class, %params) = @_;
44 $params{algorithm} ||= 'PBKDF2';
46 my $salt = $params{algorithm} =~ m/S$/ ? $params{login} : '';
48 if ($params{algorithm} =~ m/^SHA256/) {
49 return '{' . $params{algorithm} . '}' . Digest::SHA::sha256_hex($salt . $params{password});
51 } elsif ($params{algorithm} =~ m/^PBKDF2/) {
52 return $class->hash_pkkdf2(password => $params{password}, stored_password => $params{stored_password});
55 croak 'Unsupported hash algorithm ' . $params{algorithm};
59 sub hash_if_unhashed {
60 my ($class, %params) = @_;
62 my ($algorithm, $password) = $class->parse($params{password}, 'NONE');
64 return $params{password} unless $algorithm eq 'NONE';
66 if ($params{look_up_algorithm}) {
67 my $stored_password = $params{auth}->get_stored_password($params{login});
68 my ($stored_algorithm) = $class->parse($stored_password);
69 $params{algorithm} = $stored_algorithm;
72 return $class->hash(%params);
76 my ($class, $password, $default_algorithm) = @_;
78 return ($1, $2) if $password =~ m/^\{ ([^\}]+) \} (.+)/x;
79 return ($default_algorithm || 'PBKDF2', $password);