summaryrefslogtreecommitdiff
path: root/lib/App/Raps2/Password.pm
blob: 10431ed7688b606bf8bd4602eb05d4ed4b9fbb03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package App::Raps2::Password;

use strict;
use warnings;
use autodie;
use 5.010;

use Carp 'confess';
use Crypt::CBC;
use Crypt::Eksblowfish;
use Crypt::Eksblowfish::Bcrypt qw(bcrypt_hash en_base64 de_base64);

our $VERSION = '0.2';

sub new {
	my ($obj, %conf) = @_;

	$conf{cost} //= 12;

	if (not (defined $conf{salt} and length($conf{salt}) == 16)) {
		confess('incorrect salt length');
	}

	if (not (defined $conf{passphrase} and length $conf{passphrase})) {
		confess('no passphrase given');
	}

	my $ref = \%conf;

	return bless($ref, $obj);
}

sub salt {
	my ($self, $salt) = @_;

	if (not (defined $salt and length($salt) == 16)) {
		confess('incorrect salt length');
	}

	$self->{salt} = $salt;
}

sub encrypt {
	my ($self, $in) = @_;

	my $eksblowfish = Crypt::Eksblowfish->new(
		$self->{cost},
		$self->{salt},
		$self->{passphrase},
	);
	my $cbc = Crypt::CBC->new(-cipher => $eksblowfish);

	return $cbc->encrypt_hex($in);
}

sub decrypt {
	my ($self, $in) = @_;

	my $eksblowfish = Crypt::Eksblowfish->new(
		$self->{cost},
		$self->{salt},
		$self->{passphrase},
	);
	my $cbc = Crypt::CBC->new(-cipher => $eksblowfish);

	return $cbc->decrypt_hex($in);
}

sub crypt {
	my ($self) = @_;

	return en_base64(
		bcrypt_hash({
				key_nul => 1,
				cost => $self->{cost},
				salt => $self->{salt},
			},
			$self->{passphrase},
	));
}

sub verify {
	my ($self, $testhash) = @_;

	my $myhash = $self->crypt();

	if ($testhash eq $myhash) {
		return 1;
	}
	confess('Passwords did not match');
}

1;