Botan 1.10.17
arc4.cpp
Go to the documentation of this file.
1/*
2* ARC4
3* (C) 1999-2007 Jack Lloyd
4*
5* Distributed under the terms of the Botan license
6*/
7
8#include <botan/arc4.h>
9#include <botan/internal/xor_buf.h>
10#include <botan/parsing.h>
11
12namespace Botan {
13
14/*
15* Combine cipher stream with message
16*/
17void ARC4::cipher(const byte in[], byte out[], size_t length)
18 {
19 while(length >= buffer.size() - position)
20 {
21 xor_buf(out, in, &buffer[position], buffer.size() - position);
22 length -= (buffer.size() - position);
23 in += (buffer.size() - position);
24 out += (buffer.size() - position);
25 generate();
26 }
27 xor_buf(out, in, &buffer[position], length);
28 position += length;
29 }
30
31/*
32* Generate cipher stream
33*/
34void ARC4::generate()
35 {
36 byte SX, SY;
37 for(size_t i = 0; i != buffer.size(); i += 4)
38 {
39 SX = state[X+1]; Y = (Y + SX) % 256; SY = state[Y];
40 state[X+1] = SY; state[Y] = SX;
41 buffer[i] = state[(SX + SY) % 256];
42
43 SX = state[X+2]; Y = (Y + SX) % 256; SY = state[Y];
44 state[X+2] = SY; state[Y] = SX;
45 buffer[i+1] = state[(SX + SY) % 256];
46
47 SX = state[X+3]; Y = (Y + SX) % 256; SY = state[Y];
48 state[X+3] = SY; state[Y] = SX;
49 buffer[i+2] = state[(SX + SY) % 256];
50
51 X = (X + 4) % 256;
52 SX = state[X]; Y = (Y + SX) % 256; SY = state[Y];
53 state[X] = SY; state[Y] = SX;
54 buffer[i+3] = state[(SX + SY) % 256];
55 }
56 position = 0;
57 }
58
59/*
60* ARC4 Key Schedule
61*/
62void ARC4::key_schedule(const byte key[], size_t length)
63 {
64 clear();
65
66 for(size_t i = 0; i != 256; ++i)
67 state[i] = static_cast<byte>(i);
68
69 for(size_t i = 0, state_index = 0; i != 256; ++i)
70 {
71 state_index = (state_index + key[i % length] + state[i]) % 256;
72 std::swap(state[i], state[state_index]);
73 }
74
75 for(size_t i = 0; i <= SKIP; i += buffer.size())
76 generate();
77
78 position += (SKIP % buffer.size());
79 }
80
81/*
82* Return the name of this type
83*/
84std::string ARC4::name() const
85 {
86 if(SKIP == 0) return "ARC4";
87 if(SKIP == 256) return "MARK-4";
88 else return "RC4_skip(" + to_string(SKIP) + ")";
89 }
90
91/*
92* Clear memory of sensitive data
93*/
95 {
96 zeroise(state);
97 zeroise(buffer);
98 position = X = Y = 0;
99 }
100
101/*
102* ARC4 Constructor
103*/
104ARC4::ARC4(size_t s) : SKIP(s),
105 state(256),
106 buffer(DEFAULT_BUFFERSIZE)
107 {
108 clear();
109 }
110
111}
void clear()
Definition arc4.cpp:94
void cipher(const byte in[], byte out[], size_t length)
Definition arc4.cpp:17
std::string name() const
Definition arc4.cpp:84
ARC4(size_t skip=0)
Definition arc4.cpp:104
size_t size() const
Definition secmem.h:29
void zeroise(MemoryRegion< T > &vec)
Definition secmem.h:428
std::string to_string(u64bit n, size_t min_len)
Definition parsing.cpp:42
void xor_buf(byte out[], const byte in[], size_t length)
Definition xor_buf.h:21
void swap(Botan::MemoryRegion< T > &x, Botan::MemoryRegion< T > &y)
Definition secmem.h:438