epic-s6ts
[kivitendo-erp.git] / SL / Auth / Password.pm
1 package SL::Auth::Password;
2
3 use strict;
4
5 use Carp;
6 use Digest::SHA ();
7 use Encode ();
8 use PBKDF2::Tiny ();
9
10 sub hash_pkkdf2 {
11   my ($class, %params) = @_;
12
13   # PBKDF2::Tiny expects data to be in octets. Therefore we must
14   # encode everything we hand over (login, password) to UTF-8.
15
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
20   # in the database is:
21
22   # {PBKDF2}salt-in-hex:hash-in-hex
23
24   my $salt;
25
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];
28
29   } else {
30     my @login  = map { ord } split m{}, Encode::encode('utf-8', $params{login});
31     my @random = map { int(rand(256)) } (0..16);
32
33     $salt      = join '', map { sprintf '%02x', $_ } @login, @random;
34   }
35
36   my $hashed = "{PBKDF2}${salt}:" . join('', map { sprintf '%02x', ord } split m{}, PBKDF2::Tiny::derive('SHA-256', $salt, Encode::encode('utf-8', $params{password})));
37
38   return $hashed;
39 }
40
41 sub hash {
42   my ($class, %params) = @_;
43
44   $params{algorithm} ||= 'PBKDF2';
45
46   my $salt = $params{algorithm} =~ m/S$/ ? $params{login} : '';
47
48   if ($params{algorithm} =~ m/^SHA256/) {
49     return '{' . $params{algorithm} . '}' . Digest::SHA::sha256_hex($salt . $params{password});
50
51   } elsif ($params{algorithm} =~ m/^PBKDF2/) {
52     return $class->hash_pkkdf2(password => $params{password}, stored_password => $params{stored_password});
53
54   } else {
55     croak 'Unsupported hash algorithm ' . $params{algorithm};
56   }
57 }
58
59 sub hash_if_unhashed {
60   my ($class, %params) = @_;
61
62   my ($algorithm, $password) = $class->parse($params{password}, 'NONE');
63
64   return $params{password} unless $algorithm eq 'NONE';
65
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;
70   }
71
72   return $class->hash(%params);
73 }
74
75 sub parse {
76   my ($class, $password, $default_algorithm) = @_;
77
78   return ($1, $2) if $password =~ m/^\{ ([^\}]+) \} (.+)/x;
79   return ($default_algorithm || 'PBKDF2', $password);
80 }
81
82 1;