Yenta/Crypto.pm untested

filter: Statementstmt 0.0% 0 / 64 Branchbran 0.0% 0 / 6 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 87 CC 4 SCAR 15.1
CC
4
Cov
0%
decrypt
12.0
encrypt
6.0
new
2.0
CRAP 4.5
1 # -*- perl -*-
2  
3 # Copyright (c) 2010 AdCopy
4 # Author: Jeff Weisberg
5 # Created: 2010-Jun-16 10:50 (EDT)
6 # Function:
7 #
8 # $Id$
9  
10 package AC::Yenta::Crypto;
11 use AC::Yenta::Debug 'crypto';
12 use AC::Misc;
13 use Time::HiRes 'time';
14 use Crypt::Rijndael;
15 use Digest::SHA qw(sha256 hmac_sha256_base64);
16 use strict;
17  
18 require 'AC/protobuf/auth.pl';
19  
20 my $ALGORITHM = 'x-acy-aes-1';
21  
22 sub new {
23 my $class = shift;
24 my $secret = shift;
25  
26 return bless {
27 secret => $secret,
28 }, $class;
29 }
30  
31 sub encrypt {
32 my $me = shift;
33 my $buf = shift;
34  
35 my $seqno = int( time() * 1_000_000 );
36 my $nonce = random_text(48);
37 my $key = $me->_key($seqno, $nonce);
38 my $iv = $me->_iv($key, $seqno, $nonce);
39  
40 # pad
41 my $pbuf = $buf;
42 $pbuf .= "\0" x (16 - length($pbuf) & 0xF) if length($pbuf) & 0xF;
43  
44 my $aes = Crypt::Rijndael->new( $key, Crypt::Rijndael::MODE_CBC );
45 $aes->set_iv( $iv );
46 my $ct = $aes->encrypt( $pbuf );
47 my $hmac = hmac_sha256_base64($ct, $key);
48  
49 my $eb = ACPEncrypt->encode( {
50 algorithm => $ALGORITHM,
51 seqno => $seqno,
52 nonce => $nonce,
53 hmac => $hmac,
54 length => length($buf),
55 ciphertext => $ct,
56 } );
57  
58 debug("encrypted <$seqno,$nonce,$hmac>");
59  
60 return $eb;
61 }
62  
63 sub decrypt {
64 my $me = shift;
65 my $buf = shift;
66  
67 my $ed = ACPEncrypt->decode( $buf );
68 die "cannot decrypt: unknown alg\n" unless $ed->{algorithm} eq $ALGORITHM;
69  
70 my $seqno = $ed->{seqno},
71 my $nonce = $ed->{nonce};
72 my $key = $me->_key($seqno, $nonce);
73 my $iv = $me->_iv($key, $seqno, $nonce);
74  
75 my $hmac = hmac_sha256_base64($ed->{ciphertext}, $key);
76 die "cannot decrypt: hmac mismatch\n" unless $hmac eq $ed->{hmac};
77  
78 my $aes = Crypt::Rijndael->new( $key, Crypt::Rijndael::MODE_CBC );
79 $aes->set_iv( $iv );
80 my $pt = substr($aes->decrypt( $ed->{ciphertext} ), 0, $ed->{length});
81  
82 debug("decrypted <$seqno,$nonce,$hmac>");
83  
84 return $pt;
85 }
86  
87  
88 sub _key {
89 my $me = shift;
90 my $seqno = shift;
91 my $nonce = shift;
92  
93 return sha256( 'key1' . $me->{secret} . $seqno . $nonce . '1yek' );
94 }
95  
96 sub _iv {
97 my $me = shift;
98 my $key = shift;
99 my $seqno = shift;
100 my $nonce = shift;
101  
102 return substr(sha256( 'iv' . $key . $seqno ), 0, 16);
103 }
104  
105  
106 1;
107