2019-11-04 14:04:25 +00:00
|
|
|
#include <qpdf/RC4_native.hh>
|
2022-02-04 21:31:31 +00:00
|
|
|
|
2019-06-21 03:35:23 +00:00
|
|
|
#include <qpdf/QIntC.hh>
|
2008-04-29 12:55:25 +00:00
|
|
|
|
|
|
|
#include <string.h>
|
|
|
|
|
2022-04-02 21:14:10 +00:00
|
|
|
static void
|
|
|
|
swap_byte(unsigned char& a, unsigned char& b)
|
2008-04-29 12:55:25 +00:00
|
|
|
{
|
|
|
|
unsigned char t;
|
|
|
|
|
|
|
|
t = a;
|
|
|
|
a = b;
|
|
|
|
b = t;
|
|
|
|
}
|
|
|
|
|
2019-11-04 14:04:25 +00:00
|
|
|
RC4_native::RC4_native(unsigned char const* key_data, int key_len)
|
2008-04-29 12:55:25 +00:00
|
|
|
{
|
2022-04-02 21:14:10 +00:00
|
|
|
if (key_len == -1) {
|
2023-05-21 17:35:09 +00:00
|
|
|
key_len = QIntC::to_int(strlen(reinterpret_cast<char const*>(key_data)));
|
2008-04-29 12:55:25 +00:00
|
|
|
}
|
|
|
|
|
2022-04-02 21:14:10 +00:00
|
|
|
for (int i = 0; i < 256; ++i) {
|
2019-06-21 03:35:23 +00:00
|
|
|
key.state[i] = static_cast<unsigned char>(i);
|
2008-04-29 12:55:25 +00:00
|
|
|
}
|
|
|
|
key.x = 0;
|
|
|
|
key.y = 0;
|
|
|
|
|
|
|
|
int i1 = 0;
|
|
|
|
int i2 = 0;
|
2022-04-02 21:14:10 +00:00
|
|
|
for (int i = 0; i < 256; ++i) {
|
2022-02-08 14:18:08 +00:00
|
|
|
i2 = (key_data[i1] + key.state[i] + i2) % 256;
|
|
|
|
swap_byte(key.state[i], key.state[i2]);
|
|
|
|
i1 = (i1 + 1) % key_len;
|
2008-04-29 12:55:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
2023-05-21 17:35:09 +00:00
|
|
|
RC4_native::process(unsigned char const* in_data, size_t len, unsigned char* out_data)
|
2008-04-29 12:55:25 +00:00
|
|
|
{
|
2022-04-02 21:14:10 +00:00
|
|
|
for (size_t i = 0; i < len; ++i) {
|
2022-02-08 14:18:08 +00:00
|
|
|
key.x = static_cast<unsigned char>((key.x + 1) % 256);
|
|
|
|
key.y = static_cast<unsigned char>((key.state[key.x] + key.y) % 256);
|
|
|
|
swap_byte(key.state[key.x], key.state[key.y]);
|
|
|
|
int xor_index = (key.state[key.x] + key.state[key.y]) % 256;
|
|
|
|
out_data[i] = in_data[i] ^ key.state[xor_index];
|
2008-04-29 12:55:25 +00:00
|
|
|
}
|
|
|
|
}
|