1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
|
/*
* Counter mode
* (C) 1999-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/ctr.h>
#include <botan/internal/xor_buf.h>
namespace Botan {
/*
* CTR-BE Constructor
*/
CTR_BE::CTR_BE(BlockCipher* ciph) :
permutation(ciph),
counter(256 * permutation->block_size()),
buffer(counter.size()),
position(0)
{
}
/*
* CTR_BE Destructor
*/
CTR_BE::~CTR_BE()
{
delete permutation;
}
/*
* Zeroize
*/
void CTR_BE::clear()
{
permutation->clear();
zeroise(buffer);
zeroise(counter);
position = 0;
}
/*
* Set the key
*/
void CTR_BE::key_schedule(const byte key[], size_t key_len)
{
permutation->set_key(key, key_len);
// Set a default all-zeros IV
set_iv(0, 0);
}
/*
* Return the name of this type
*/
std::string CTR_BE::name() const
{
return ("CTR-BE(" + permutation->name() + ")");
}
/*
* CTR-BE Encryption/Decryption
*/
void CTR_BE::cipher(const byte in[], byte out[], size_t length)
{
while(length >= buffer.size() - position)
{
xor_buf(out, in, &buffer[position], buffer.size() - position);
length -= (buffer.size() - position);
in += (buffer.size() - position);
out += (buffer.size() - position);
increment_counter();
}
xor_buf(out, in, &buffer[position], length);
position += length;
}
/*
* Set CTR-BE IV
*/
void CTR_BE::set_iv(const byte iv[], size_t iv_len)
{
if(!valid_iv_length(iv_len))
throw Invalid_IV_Length(name(), iv_len);
const size_t BLOCK_SIZE = permutation->block_size();
zeroise(counter);
counter.copy(0, iv, iv_len);
for(size_t i = 1; i != 256; ++i)
{
counter.copy(i*BLOCK_SIZE,
&counter[(i-1)*BLOCK_SIZE],
BLOCK_SIZE);
for(size_t j = 0; j != BLOCK_SIZE; ++j)
if(++counter[i*BLOCK_SIZE + (BLOCK_SIZE-1-j)])
break;
}
permutation->encrypt_n(&counter[0], &buffer[0], 256);
position = 0;
}
/*
* Increment the counter and update the buffer
*/
void CTR_BE::increment_counter()
{
const size_t BLOCK_SIZE = permutation->block_size();
for(size_t i = 0; i != 256; ++i)
{
for(size_t j = 1; j != BLOCK_SIZE; ++j)
if(++counter[i*BLOCK_SIZE + (BLOCK_SIZE-1-j)])
break;
}
permutation->encrypt_n(&counter[0], &buffer[0], 256);
position = 0;
}
}
|