diff --git a/lib/AccountManager/Tools.pm b/lib/AccountManager/Tools.pm index 5e148515fd5a6870e39044952685c099b2a6a54c..c4a698fad0c2659b723b963571f3447fd256e26a 100644 --- a/lib/AccountManager/Tools.pm +++ b/lib/AccountManager/Tools.pm @@ -4,7 +4,6 @@ use strict; use warnings; use Digest::SHA; -use Digest::MD5; use Encode; use English qw(-no_match_vars); use List::Util qw(shuffle); @@ -48,10 +47,10 @@ sub sha256_hash { return Digest::SHA::sha256_base64($s); } -# This function generates a random password sub generate_password { - my $size = 10; + my ($size) = @_; + # define alphabet my @uppers = ('A' .. 'N', 'P' .. 'Z'); my @lowers = ('a' .. 'k', 'm' .. 'z'); my @punctuations = (':', '!', '?', '&', '$', '=', '-', '#'); @@ -74,13 +73,21 @@ sub generate_password { return join('', shuffle(@chars)); } -# ID is based on time + PID -sub generate_token { - my ($salt, $size) = @_; - $salt = $PID unless $salt; - $size = 20 unless $size; +sub generate_secret { + my ($size) = @_; - return substr(Digest::MD5::md5_hex(time . $salt), -1 * $size); + # define alphabet + my @lowers = ('a' .. 'k', 'm' .. 'z'); + my @numerics = ('0' .. '9'); + my @all = (@lowers, @numerics); + + # fill characters list + my @chars; + for my $i (1 .. $size) { + push(@chars, $all[ rand @all ]); + } + + return join('', shuffle(@chars)); } ## Updates simpleSamlPhp authsources.php configuration file diff --git a/t/tools.t b/t/tools.t index c33216e862254547b86f41c311b1d63a5926a186..8452f7338bc516fcafbee0cc17d1953550c3ea69 100644 --- a/t/tools.t +++ b/t/tools.t @@ -8,16 +8,20 @@ use Test::More; use AccountManager::Tools; -plan tests => 4; +plan tests => 5; -my $key = AccountManager::Tools::generate_token(undef, 10); -my $secret = AccountManager::Tools::generate_password(); +my $key = AccountManager::Tools::generate_secret(10); +my $password = AccountManager::Tools::generate_password(10); -ok($key ne $secret, 'key and secret are random strings'); -ok(length($key) == length($secret), 'key and secret have same size'); +ok(length($password) == 10, 'password has expected size'); +ok(length($key) == 10, 'key has expected size'); + +ok($key ne $password, 'key and passwords are random strings'); + +my $encrypted_password = AccountManager::Tools::encrypt($password, $key); +ok($encrypted_password ne $password, 'encrypted password differs from password'); + +my $decrypted_password = AccountManager::Tools::decrypt($encrypted_password, $key); +ok($decrypted_password eq $password, 'decrypted password matches password'); -my $encrypted_secret = AccountManager::Tools::encrypt($secret, $key); -ok($encrypted_secret ne $secret, 'crypted_secret and secret are differents'); -my $decrypted_secret = AccountManager::Tools::decrypt($encrypted_secret, $key); -ok($decrypted_secret eq $secret, 'decrypted_secret and secret are equals');