1 package SL::Auth::Password;
8 my ($class, %params) = @_;
10 if (!$params{algorithm}) {
11 $params{algorithm} = 'SHA256S';
12 $params{fallback_algorithm} = 'MD5';
16 my $salt = $params{algorithm} =~ m/S$/ ? $params{login} : '';
18 if ($params{algorithm} =~ m/^SHA256/) {
19 if (eval { require Digest::SHA; 1 }) {
20 return '{' . $params{algorithm} . '}' . Digest::SHA::sha256_hex($salt . $params{password});
22 } elsif ($params{fallback_algorithm}) {
23 return $class->hash(%params, algorithm => $params{fallback_algorithm});
26 die 'Digest::SHA is not available';
29 } elsif ($params{algorithm} =~ m/^SHA1/) {
30 if (eval { require Digest::SHA; 1 }) {
31 return '{' . $params{algorithm} . '}' . Digest::SHA::sha1_hex($salt . $params{password});
33 } elsif (eval { require Digest::SHA1; 1 }) {
34 return '{' . $params{algorithm} . '}' . Digest::SHA1::sha1_hex($salt . $params{password});
36 } elsif ($params{fallback_algorithm}) {
37 return $class->hash(%params, algorithm => $params{fallback_algorithm});
40 die 'Neither Digest::SHA nor Digest::SHA1 is available';
43 } elsif ($params{algorithm} =~ m/^MD5/) {
45 return '{' . $params{algorithm} . '}' . Digest::MD5::md5_hex($salt . $params{password});
47 } elsif ($params{algorithm} eq 'CRYPT') {
48 return '{CRYPT}' . crypt($params{password}, substr($params{login}, 0, 2));
51 croak 'Unsupported hash algorithm ' . $params{algorithm};
55 sub hash_if_unhashed {
56 my ($class, %params) = @_;
58 my ($algorithm, $password) = $class->parse($params{password}, 'NONE');
60 return $params{password} unless $algorithm eq 'NONE';
62 if ($params{look_up_algorithm}) {
63 my $stored_password = $params{auth}->get_stored_password($params{login});
64 my ($stored_algorithm) = $class->parse($stored_password);
65 $params{algorithm} = $stored_algorithm;
68 return $class->hash(%params);
72 my ($class, $password, $default_algorithm) = @_;
74 return ($1, $2) if $password =~ m/^\{ ([^\}]+) \} (.+)/x;
75 return ($default_algorithm || 'CRYPT', $password);