Passwort-Hashing in eigenes Modul ausgelagert
[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 parse {
39   my ($class, $password) = @_;
40
41   return ($1, $2) if $password =~ m/^\{ ([^\}]+) \} (.+)/x;
42   return ('CRYPT', $password);
43 }
44
45 1;