blib/lib/OpusVL/SimpleCrypto.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 package OpusVL::SimpleCrypto;
4  
5 # ABSTRACT: Very simple encryption methods.
6  
7 2 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use Crypt::Sodium;
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use MIME::Base64;
10  
11 our $VERSION = '0.008';
12  
13 has key_string => (is => 'rw', lazy => 1, builder => '_build_key_string');
14 has key => (is => 'ro', lazy => 1, builder => '_build_key');
15 has deterministic_salt => (is => 'ro', lazy => 1, builder => '_build_deterministic_salt');
16 has deterministic_salt_string => (is => 'ro', lazy => 1, builder => '_build_deterministic_salt_string');
17  
18 sub _build_deterministic_salt
19 {
20 my $self = shift;
21 die 'Must specify deterministic_salt or deterministic_salt_string' unless $self->deterministic_salt_string;
22 return decode_base64($self->deterministic_salt_string);
23 }
24  
25 sub _build_deterministic_salt_string
26 {
27 my $self = shift;
28 die 'Must specify deterministic_salt or deterministic_salt_string' unless $self->deterministic_salt;
29 return encode_base64($self->deterministic_salt);
30 }
31  
32 sub _build_key
33 {
34 my $self = shift;
35 die 'Must specify key or key_string' unless $self->key_string;
36 return decode_base64($self->key_string);
37 }
38  
39 sub _build_key_string
40 {
41 my $self = shift;
42 die 'Must specify key or key_string' unless $self->key;
43 return encode_base64($self->key);
44 }
45  
46 sub GenerateKey
47 {
48 my $k = crypto_stream_key();
49 my $salt = crypto_pwhash_salt();
50 return OpusVL::SimpleCrypto->new({ key => $k, deterministic_salt => $salt });
51 }
52  
53 sub encrypt
54 {
55 my $self = shift;
56 my $message = shift;
57 my $n = crypto_stream_nonce();
58 my $t = crypto_secretbox($message, $n, $self->key);
59 return sprintf("%s:%s", encode_base64($n), encode_base64($t));
60 }
61  
62 sub encrypt_deterministic
63 {
64 my $self = shift;
65 my $message = shift;
66 my $salt = $self->deterministic_salt;
67 my $n = crypto_pwhash_scrypt($message, $salt, crypto_stream_NONCEBYTES);
68 my $t = crypto_secretbox($message, $n, $self->key);
69 return sprintf("%s:%s", encode_base64($n), encode_base64($t));
70 }
71  
72 sub decrypt
73 {
74 my $self = shift;
75 my $ciphertext = shift;
76 my ($nonce, $cipher) = split /:/, $ciphertext;
77 return crypto_secretbox_open(decode_base64($cipher), decode_base64($nonce), $self->key);
78 }
79  
80  
81 1;
82  
83 __END__
↑ Summary