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