]> Dogcows Code - chaz/p5-File-KDBX/blob - t/crypt.t
576f7085ed2ba883ce7aec16b9f6aa25546e74a3
[chaz/p5-File-KDBX] / t / crypt.t
1 #!/usr/bin/env perl
2
3 use warnings;
4 use strict;
5
6 use lib 't/lib';
7 use TestCommon;
8
9 use Crypt::Misc 0.029 qw(decode_b64 encode_b64);
10 use File::KDBX::Constants qw(CIPHER_UUID_AES256);
11 use IO::Handle;
12 use Test::More;
13
14 BEGIN { use_ok 'File::KDBX::Cipher' }
15 BEGIN { use_ok 'PerlIO::via::File::KDBX::Crypt' }
16
17 subtest 'Round-trip block stream' => sub {
18 plan tests => 3;
19 my $block_cipher = File::KDBX::Cipher->new(uuid => CIPHER_UUID_AES256, key => 0x01 x 32, iv => 0x01 x 16);
20 test_roundtrip($block_cipher,
21 'Smell the pretty flowers.',
22 decode_b64('pB10mV+mhTuh7bKg0KEUl5H1ajFMaP4uPnTZNcDgq6s='),
23 );
24 };
25
26 subtest 'Round-trip cipher stream' => sub {
27 plan tests => 3;
28 my $cipher_stream = File::KDBX::Cipher->new(stream_id => 2, key => 0x01 x 16);
29 test_roundtrip($cipher_stream,
30 'Smell the pretty flowers.',
31 decode_b64('gNj2Ud9tWtFDy+xDN/U01RxmCoI6MAlTKQ=='),
32 );
33 };
34
35 subtest 'Error handling' => sub {
36 plan tests => 3;
37
38 my $block_cipher = File::KDBX::Cipher->new(uuid => CIPHER_UUID_AES256, key => 0x01 x 32, iv => 0x01 x 16);
39 pipe(my $read, my $write) or die "pipe failed: $!";
40 PerlIO::via::File::KDBX::Crypt->push($read, $block_cipher);
41
42 print $write 'blah blah blah!!';
43 close($write) or die "close failed: $!";
44
45 is $read->error, 0, 'Read handle starts out fine';
46 my $plaintext = do { local $/; <$read> };
47 is $read->error, 1, 'Read handle can enter and error state';
48
49 like $PerlIO::via::File::KDBX::Crypt::ERROR, qr/fatal/i,
50 'Error object is available';
51 };
52
53 done_testing;
54 exit;
55
56 sub test_roundtrip {
57 my $cipher = shift;
58 my $expected_plaintext = shift;
59 my $expected_ciphertext = shift;
60
61 pipe(my $read, my $write) or die "pipe failed: $!";
62 PerlIO::via::File::KDBX::Crypt->push($write, $cipher);
63
64 print $write $expected_plaintext;
65 binmode($write, ':pop'); # finish stream
66 close($write) or die "close failed: $!";
67
68 my $ciphertext = do { local $/; <$read> };
69 close($read);
70 is $ciphertext, $expected_ciphertext, 'Encrypted a string'
71 or diag encode_b64($ciphertext);
72
73 my $ciphertext2 = $cipher->encrypt_finish($expected_plaintext);
74 is $ciphertext, $ciphertext2, 'Same result';
75
76 open(my $fh, '<', \$ciphertext) or die "open failed: $!\n";
77 PerlIO::via::File::KDBX::Crypt->push($fh, $cipher);
78
79 my $plaintext = do { local $/; <$fh> };
80 close($fh);
81 is $plaintext, $expected_plaintext, 'Decrypted a string'
82 or diag encode_b64($plaintext);
83 }
This page took 0.040766 seconds and 3 git commands to generate.