Skip to content
Snippets Groups Projects
Tools.pm 3.03 KiB
package AccountManager::Tools;

use strict;
use warnings;

use Digest::SHA;
use Encode;
use English qw(-no_match_vars);
use List::Util qw(shuffle);
use List::MoreUtils qw(pairwise);
use MIME::Base64;
use Template;
use Template::Constants qw(:chomp);

use AccountManager::Template::Plugin::Quote;

sub encrypt {
    my ($string, $key) = @_;

    my @string_chars = split(//, $string);
    my @key_chars    = split(//, $key);

    return encode_base64(otp(\@string_chars, \@key_chars));
}

sub decrypt {
    my ($string, $key) = @_;

    my @string_chars = split(//, decode_base64($string));
    my @key_chars = split(//, $key);

    return otp(\@string_chars, \@key_chars);
}

sub otp {
    my ($string, $key) = @_;

    my @chars =
        pairwise { chr(ord($a) ^ ord($b)) }
        @$string,
        @$key;

    return join('', @chars);
}

# get SHA256 hash for a string
sub sha256_hash {
    my ($s) = @_;

    return Digest::SHA::sha256_base64($s);
}

sub generate_password {
    my ($size) = @_;

    # define alphabet
    my @uppers       = ('A' .. 'N', 'P' .. 'Z');
    my @lowers       = ('a' .. 'k', 'm' .. 'z');
    my @punctuations = (':', '!', '?', '&', '$', '=', '-', '#');
    my @numerics     = ('0' .. '9');
    my @all          = (@uppers, @lowers, @punctuations, @numerics);

    # start with a random character of each class
    my @chars = (
        $uppers[ rand @uppers ],
        $lowers[ rand @lowers ],
        $punctuations[ rand @punctuations ],
        $numerics[ rand @numerics ]
    );