summaryrefslogtreecommitdiff
path: root/lib/App/Raps2/Password.pm
blob: 73258b26d37a7287a5196cd02fbdeff27850785a (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package App::Raps2::Password;

use strict;
use warnings;
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}) {
		$conf{salt} = create_salt();
	}

	if (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 create_salt {
	my ($self) = @_;
	my $salt = q{};

	for (1 .. 16) {
		$salt .= chr(0x21 + int(rand(90)));
	}

	return $salt;
}

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

	if (not defined $salt) {
		return $self->{salt};
	}

	if (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;