Crypto/Symmetric.pm

filter: Statementstmt 98.6% 72 / 73 Branchbran 100% 26 / 26 Conditioncond 73.3% 11 / 15 MC/DCmcdc 60.0% 6 / 10 Subroutinesub 100% 10 / 10 Podpod 100% 4 / 4 totaltotal 93.4% 129 / 138 CC 19 SCAR 16.7
CC
19
Cov
96%
decrypt
8.0
reinit
7.0
encrypt
5.0
CRAP 5.3
« Crypto/RSA.pm ↑ Summary Crypto.pm »
1 ##############################################################################
2 #
3 # Data::Tools::Crypto::Symmetric perl module
4 # Copyright (c) 2013-2026 Vladi Belperchinov-Shabanski "Cade"
5 # <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
6 # http://cade.noxrun.com/
7 #
8 # GPL
9 #
10 ##############################################################################
11 #
12 # freeze/thaw API actually uses JSON as safer option than Storable
13 #
14 ##############################################################################
15 package Data::Tools::Crypto::Symmetric;
16 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 6 ▶use parent 'Data::Tools::Crypto';
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 6 ▶use Encode qw( encode_utf8 decode_utf8 );
Subroutine BEGIN: called CC=1 SCAR=0.0
21 6 ▶use Exception::Sink;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 6 ▶use Crypt::AuthEnc::ChaCha20Poly1305 qw( chacha20poly1305_encrypt_authenticate chacha20poly1305_decrypt_verify );
Subroutine BEGIN: called CC=1 SCAR=0.0
23 6 ▶use Crypt::PRNG qw( random_bytes );
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 6 our $VERSION = '1.53';
26  
27 6 my $NONCE_LEN = 12;
28 6 my $TAG_LEN = 16;
29 6 my $FLAG_LEN = 1;
30  
31 sub new
32 2191 ▶{
Subroutine new: called CC=2 SCAR=7.1
Pod documented
33 2191 my $class = shift;
34 2191 my $key = shift;
35 2191 my %opt = @_;
36  
37 2191 ▶ $class = ref( $class ) || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
021910
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
38 2191 my $self = {};
39 2191 bless $self, $class;
40  
41 2191 $self->reinit( $key, %opt );
42  
43 2156 return $self;
44 }
45  
46 # sub DESTROY
47 # {
48 # my $self = shift;
49 # }
50  
51 ##############################################################################
52  
53 # empty for now...
54 0 my %KNOWN_OPT = map { $_ => 1 } qw( );
55  
56 sub reinit
57 2204 ▶{
Subroutine reinit: called CC=7 SCAR=19.5
Pod documented
58 2204 my $self = shift;
59 2204 my $key = shift;
60 2204 my %opt = @_;
61  
62 2204 %$self = (); # clear state
63  
64 2204 my @unknown = grep { ! $KNOWN_OPT{ $_ } } keys %opt;
65 2204 ▶ boom( "unknown option(s) [" . join( ',', sort @unknown ) . "]" ) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 11 2193 2204
66  
67 2193 ▶ boom( "key parameter is not defined or empty" ) unless defined $key and $key ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and $key ne "" 10 2183 2193
Condition100%3/3
defined $key and $key ne ""
!ll&&!rl&&r
552183
MC/DC100%2/2
defined $key and $key ne ""
defined $key $key ne ""
Truth table100%3/3
A and B
A= defined $keyB= $key ne ""
ABresult
0X0
100
111
68 2183 ▶ boom( "key parameter cannot be downgraded from UTF-8" ) if utf8::is_utf8( $key ) and ! utf8::downgrade( $key, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($key) and not utf8::downgrade($key, 1) 5 2178 2183
Condition100%3/3
utf8::is_utf8($key) and not utf8::downgrade($key, 1)
!ll&&!rl&&r
217355
MC/DC100%2/2
utf8::is_utf8($key) and not utf8::downgrade($key, 1)
utf8::is_utf8($key) not utf8::downgrade($key, 1)
Truth table100%3/3
A and not(B)
A= utf8::is_utf8($key)B= not utf8::downgrade($key, 1)
ABresult
0X0
100
111
69 2178 my $kl = length( $key );
70 2178 ▶ boom( "invalid key size, expected 32 bytes, got [$kl]" ) unless $kl == 32;
Branch: 1 branch
BranchTrueFalseTotal
unless $kl == 32 18 2160 2178
71  
72 2160 $self->{ 'KEY' } = $key;
73  
74 2160 1;
75 }
76  
77 ##############################################################################
78  
79 sub encrypt
80 21848 ▶{
Subroutine encrypt: called CC=5 SCAR=16.1
Pod documented
81 21848 my $self = shift;
82 21848 my $ptext = shift; # plaintext
83  
84 21848 ▶ boom( "object state is undefined! use reinit() to setup first" ) unless defined $self->{ 'KEY' } and $self->{ 'KEY' } ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"KEY"} and $self->{"KEY"} ne "" 1 21847 21848
Condition66%2/3
defined $self->{"KEY"} and $self->{"KEY"} ne ""
!ll&&!rl&&r
1021847
MC/DC50%1/2
defined $self->{"KEY"} and $self->{"KEY"} ne ""
defined $self->{"KEY"} $self->{"KEY"} ne ""
Truth table66%2/3
A and B
A= defined $self->{"KEY"}B= $self->{"KEY"} ne ""
ABresult
0X0
100
111
85 21847 ▶ boom( "plaintext not defined" ) unless defined( $ptext );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ptext 1 21846 21847
86  
87 21846 my $flag = 'b'; # binary
88 21846 ▶ if( utf8::is_utf8( $ptext ) )
Branch: 1 branch
BranchTrueFalseTotal
if (utf8::is_utf8($ptext)) 5660 16186 21846
89 {
90 5660 $flag = 'u';
91 5660 $ptext = encode_utf8( $ptext );
92 }
93  
94 21846 my $nonce = random_bytes( $NONCE_LEN );
95 21846 my ( $ctext, $tag ) = chacha20poly1305_encrypt_authenticate( $self->{ 'KEY' }, $nonce, undef, $flag . $ptext );
96 21846 return $nonce . $ctext . $tag;
97 }
98  
99 sub decrypt
100 11372 ▶{
Subroutine decrypt: called CC=8 SCAR=20.8
Pod documented
101 11372 my $self = shift;
102 11372 my $ctext = shift; # cryptotext
103  
104 11372 ▶ boom( "object state is undefined! use reinit() to setup first" ) unless defined $self->{ 'KEY' } and $self->{ 'KEY' } ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"KEY"} and $self->{"KEY"} ne "" 4 11368 11372
Condition66%2/3
defined $self->{"KEY"} and $self->{"KEY"} ne ""
!ll&&!rl&&r
4011368
MC/DC50%1/2
defined $self->{"KEY"} and $self->{"KEY"} ne ""
defined $self->{"KEY"} $self->{"KEY"} ne ""
Truth table66%2/3
A and B
A= defined $self->{"KEY"}B= $self->{"KEY"} ne ""
ABresult
0X0
100
111
105 11368 ▶ boom( "cryptotext not defined" ) unless defined( $ctext );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ctext 1 11367 11368
106 11367 ▶ boom( "cryptotext must be binary, utf8 scalars are not supported" ) if utf8::is_utf8( $ctext );
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($ctext) 5 11362 11367
107  
108 11362 ▶ return undef if length( $ctext ) < $NONCE_LEN + $TAG_LEN + $FLAG_LEN;
Branch: 1 branch
BranchTrueFalseTotal
if length $ctext < $NONCE_LEN + $TAG_LEN + $FLAG_LEN 10 11352 11362
109  
110 11352 my $nonce = substr( $ctext, 0, $NONCE_LEN );
111 11352 my $tag = substr( $ctext, -$TAG_LEN );
112 11352 $ctext = substr( $ctext, $NONCE_LEN, length( $ctext ) - $NONCE_LEN - $TAG_LEN );
113  
114 11352 my $ptext = chacha20poly1305_decrypt_verify( $self->{ 'KEY' }, $nonce, undef, $ctext, $tag );
115  
116 11352 ▶ return undef unless defined $ptext;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ptext 20 11332 11352
117  
118 11332 my $flag = substr( $ptext, 0, 1 );
119 11332 $ptext = substr( $ptext, 1 );
120  
121 11332 ▶ if( $flag eq 'u' )
Branch: 1 branch
BranchTrueFalseTotal
if ($flag eq "u") 5670 5662 11332
122 {
123 5670 $ptext = decode_utf8( $ptext );
124 }
125  
126 11332 return $ptext;
127 }
128  
129 ##############################################################################
130  
131 =pod
132  
133  
134 =head1 NAME
135  
136 Data::Tools::Crypto::Symmetric - authenticated symmetric encryption with a shared secret key
137  
138 =head1 SYNOPSIS
139  
140 use Data::Tools::Crypto::Symmetric;
141 use Crypt::PRNG;
142 use Exception::Sink;
143  
144 # the key is 32 raw bytes, not a passphrase
145  
146 my $key = Crypt::PRNG::random_bytes( 32 );
147 my $crypto = Data::Tools::Crypto::Symmetric->new( $key );
148  
149 # --------------------------------------------------------------------------
150  
151 my $ctext = $crypto->encrypt( $ptext );
152 my $ptext = $crypto->decrypt( $ctext );
153  
154 boom( "data cannot be decrypted" ) unless defined $ptext;
155  
156 # --------------------------------------------------------------------------
157  
158 # the whole encoding and freeze/thaw API comes from
159 # Data::Tools::Crypto, see there for the full list
160  
161 my $sealed = $crypto->freeze_base64url( { name => 'test' } );
162 my $data = $crypto->thaw_base64url( $sealed );
163  
164 # --------------------------------------------------------------------------
165  
166 # a new key can be set on an existing object
167  
168 $crypto->reinit( $another_key );
169  
170 # --------------------------------------------------------------------------
171  
172 =head1 DESCRIPTION
173  
174 Data::Tools::Crypto::Symmetric encrypts with ChaCha20-Poly1305, which is
175 authenticated: cryptotext which has been modified in any way will not decrypt
176 at all, rather than decrypting to wrong data. A fresh random nonce is used for
177 every message, so encrypting the same plaintext twice never gives the same
178 cryptotext.
179  
180 Both sides need the same secret key. If there is no way to share one, use
181 Data::Tools::Crypto::RSA instead.
182  
183 =head1 METHODS
184  
185 =head2 new( $key )
186  
187 Returns a new object. $key must be exactly 32 raw bytes, undef or an empty
188 key is refused. A key which perl
189 holds as characters is accepted if it can be represented as bytes, and is
190 converted, otherwise it is rejected -- 32 characters are not always 32 bytes.
191  
192 There are no options yet. Unknown options are refused rather than silently
193 ignored.
194  
195 =head2 reinit( $key )
196  
197 Sets a new key on an existing object. All previous state is cleared first, so
198 if the key or an option is rejected the object is left without a key and is
199 not usable until a later reinit() succeeds. Catching the exception and
200 handling the unusable object is left to the caller.
201  
202 =head2 encrypt( $plaintext )
203  
204 Returns the cryptotext, which is always binary. There is no limit on the size
205 of the plaintext, the cryptotext is 29 bytes longer than the plaintext.
206  
207 =head2 decrypt( $cryptotext )
208  
209 Returns the plaintext, or undef if the cryptotext cannot be decrypted, which
210 covers a wrong key, modified data, truncated data and random input alike.
211 There is deliberately no more detail than that: telling these cases apart
212 would help an attacker more than a caller.
213  
214 =head1 UTF8 HANDLING
215  
216 encrypt()/decrypt() are transparent. Whatever goes in comes back out, with
217 the same value, the same length and in the same form. A byte string returns as
218 a byte string and a character string returns as a character string, which are
219 not the same thing in perl even when they print identically:
220  
221 my $chars = "caf\x{e9}"; # 4 characters
222 my $bytes = "caf\xc3\xa9"; # 5 bytes, the utf8 encoding of it
223  
224 $crypto->decrypt( $crypto->encrypt( $chars ) ); # 4 characters back
225 $crypto->decrypt( $crypto->encrypt( $bytes ) ); # 5 bytes back
226  
227 Cryptotext is always binary. Passing a character string to decrypt() is a
228 mistake and raises an exception, rather than being silently mangled.
229  
230 =head1 ERRORS
231  
232 The two kinds of failure are reported differently and never confused:
233  
234 * a caller or configuration error raises an exception with boom(), i.e. a
235 missing, empty or wrong sized key, an unknown option, an undefined
236 argument, a character string where binary data is required, or any use
237 of an object whose reinit() failed
238  
239 * data which simply does not decrypt returns undef, which is a normal
240 result the caller is expected to check
241  
242 =head1 DATA FORMAT
243  
244 nonce (12 bytes) . cryptotext . authentication tag (16 bytes)
245  
246 The plaintext carries one leading marker byte, 'b' for binary or 'u' for a
247 character string, which is what makes the utf8 handling above transparent.
248 This accounts for the 29 bytes of overhead.
249  
250 =head1 REQUIRED MODULES
251  
252 Data::Tools::Crypto::Symmetric uses:
253  
254 * Data::Tools::Crypto
255 * Crypt::AuthEnc::ChaCha20Poly1305 (CryptX)
256 * Crypt::PRNG (CryptX)
257 * Encode
258 * Exception::Sink
259  
260 =head1 GITHUB REPOSITORY
261  
262 https://github.com/cade-vs/perl-data-tools-crypto
263  
264 git clone https://github.com/cade-vs/perl-data-tools-crypto.git
265  
266 =head1 AUTHOR
267  
268 Vladi Belperchinov-Shabanski "Cade"
269 <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
270 http://cade.noxrun.com/
271  
272  
273 =cut
274  
275 ##############################################################################
276  
277 6 1;
« Crypto/RSA.pm ↑ Summary Crypto.pm »