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