1 package SL::Auth::Password;
 
  12   my ($class, %params) = @_;
 
  14   # PBKDF2::Tiny expects data to be in octets. Therefore we must
 
  15   # encode everything we hand over (login, password) to UTF-8.
 
  17   # This hash method uses a random hash and not just the user's login
 
  18   # for its salt. This is due to the official recommendation that at
 
  19   # least eight octets of random data should be used. Therefore we
 
  20   # must store the salt together with the hashed password. The format
 
  23   # {PBKDF2}salt-in-hex:hash-in-hex
 
  27   if ((defined $params{stored_password}) && ($params{stored_password} =~ m/^\{PBKDF2\} ([0-9a-f]+) :/x)) {
 
  28     $salt = (split m{:}, Encode::encode('utf-8', $1), 2)[0];
 
  31     my @login  = map { ord } split m{}, Encode::encode('utf-8', $params{login});
 
  32     my @random = map { int(rand(256)) } (0..16);
 
  34     $salt      = join '', map { sprintf '%02x', $_ } @login, @random;
 
  37   my $hashed = "{PBKDF2}${salt}:" . join('', map { sprintf '%02x', ord } split m{}, PBKDF2::Tiny::derive('SHA-256', $salt, Encode::encode('utf-8', $params{password})));
 
  43   my ($class, %params) = @_;
 
  45   $params{algorithm} ||= 'PBKDF2';
 
  47   my $salt = $params{algorithm} =~ m/S$/ ? $params{login} : '';
 
  49   if ($params{algorithm} =~ m/^SHA256/) {
 
  50     return '{' . $params{algorithm} . '}' . Digest::SHA::sha256_hex($salt . $params{password});
 
  52   } elsif ($params{algorithm} =~ m/^SHA1/) {
 
  53     return '{' . $params{algorithm} . '}' . Digest::SHA::sha1_hex($salt . $params{password});
 
  55   } elsif ($params{algorithm} =~ m/^MD5/) {
 
  56     return '{' . $params{algorithm} . '}' . Digest::MD5::md5_hex($salt . $params{password});
 
  58   } elsif ($params{algorithm} eq 'CRYPT') {
 
  59     return '{CRYPT}' . crypt($params{password}, substr($params{login}, 0, 2));
 
  61   } elsif ($params{algorithm} =~ m/^PBKDF2/) {
 
  62     return $class->hash_pkkdf2(password => $params{password}, stored_password => $params{stored_password});
 
  65     croak 'Unsupported hash algorithm ' . $params{algorithm};
 
  69 sub hash_if_unhashed {
 
  70   my ($class, %params) = @_;
 
  72   my ($algorithm, $password) = $class->parse($params{password}, 'NONE');
 
  74   return $params{password} unless $algorithm eq 'NONE';
 
  76   if ($params{look_up_algorithm}) {
 
  77     my $stored_password    = $params{auth}->get_stored_password($params{login});
 
  78     my ($stored_algorithm) = $class->parse($stored_password);
 
  79     $params{algorithm}     = $stored_algorithm;
 
  82   return $class->hash(%params);
 
  86   my ($class, $password, $default_algorithm) = @_;
 
  88   return ($1, $2) if $password =~ m/^\{ ([^\}]+) \} (.+)/x;
 
  89   return ($default_algorithm || 'CRYPT', $password);