Fall 'kein Hash-Algorithmus angegeben' bei alten Passwörtern richtig behandeln
[kivitendo-erp.git] / SL / Auth / Password.pm
1 package SL::Auth::Password;
2
3 use strict;
4
5 use Carp;
6
7 sub hash {
8   my ($class, %params) = @_;
9
10   if (!$params{algorithm}) {
11     $params{algorithm}          = 'SHA1';
12     $params{fallback_algorithm} = 'MD5';
13   }
14
15   if ($params{algorithm} eq 'SHA1') {
16     if (eval { require Digest::SHA1; 1 }) {
17       return '{SHA1}' . Digest::SHA1::sha1_hex($params{password});
18
19     } elsif ($params{fallback_algorithm}) {
20       return $class->hash_password(%params, algorithm => $params{fallback_algorithm});
21
22     } else {
23       die 'Digest::SHA1 not available';
24     }
25
26   } elsif ($params{algorithm} eq 'MD5') {
27     require Digest::MD5;
28     return '{MD5}' . Digest::MD5::md5_hex($params{password});
29
30   } elsif ($params{algorithm} eq 'CRYPT') {
31     return '{CRYPT}' . crypt($params{password}, substr($params{login}, 0, 2));
32
33   } else {
34     croak 'Unsupported hash algorithm ' . $params{algorithm};
35   }
36 }
37
38 sub hash_if_unhashed {
39   my ($class, %params) = @_;
40
41   my ($algorithm, $password) = $class->parse($params{password}, 'NONE');
42
43   return $params{password} unless $algorithm eq 'NONE';
44
45   if ($params{look_up_algorithm}) {
46     my $stored_password    = $params{auth}->get_stored_password($params{login});
47     my ($stored_algorithm) = $class->parse($stored_password);
48     $params{algorithm}     = $stored_algorithm;
49   }
50
51   return $class->hash(%params);
52 }
53
54 sub parse {
55   my ($class, $password, $default_algorithm) = @_;
56
57   return ($1, $2) if $password =~ m/^\{ ([^\}]+) \} (.+)/x;
58   return ($default_algorithm || 'CRYPT', $password);
59 }
60
61 1;