mirror of
https://github.com/qpdf/qpdf.git
synced 2024-11-01 03:12:29 +00:00
d71f05ca07
This makes all integer type conversions that have potential data loss explicit with calls that do range checks and raise an exception. After this commit, qpdf builds with no warnings when -Wsign-conversion -Wconversion is used with gcc or clang or when -W3 -Wd4800 is used with MSVC. This significantly reduces the likelihood of potential crashes from bogus integer values. There are some parts of the code that take int when they should take size_t or an offset. Such places would make qpdf not support files with more than 2^31 of something that usually wouldn't be so large. In the event that such a file shows up and is valid, at least qpdf would raise an error in the right spot so the issue could be legitimately addressed rather than failing in some weird way because of a silent overflow condition.
58 lines
1.2 KiB
C++
58 lines
1.2 KiB
C++
#include <qpdf/RC4.hh>
|
|
#include <qpdf/QIntC.hh>
|
|
|
|
#include <string.h>
|
|
|
|
static void swap_byte(unsigned char &a, unsigned char &b)
|
|
{
|
|
unsigned char t;
|
|
|
|
t = a;
|
|
a = b;
|
|
b = t;
|
|
}
|
|
|
|
RC4::RC4(unsigned char const* key_data, int key_len)
|
|
{
|
|
if (key_len == -1)
|
|
{
|
|
key_len = QIntC::to_int(
|
|
strlen(reinterpret_cast<char const*>(key_data)));
|
|
}
|
|
|
|
for (int i = 0; i < 256; ++i)
|
|
{
|
|
key.state[i] = static_cast<unsigned char>(i);
|
|
}
|
|
key.x = 0;
|
|
key.y = 0;
|
|
|
|
int i1 = 0;
|
|
int i2 = 0;
|
|
for (int i = 0; i < 256; ++i)
|
|
{
|
|
i2 = (key_data[i1] + key.state[i] + i2) % 256;
|
|
swap_byte(key.state[i], key.state[i2]);
|
|
i1 = (i1 + 1) % key_len;
|
|
}
|
|
}
|
|
|
|
void
|
|
RC4::process(unsigned char *in_data, size_t len, unsigned char* out_data)
|
|
{
|
|
if (out_data == 0)
|
|
{
|
|
// Convert in place
|
|
out_data = in_data;
|
|
}
|
|
|
|
for (size_t i = 0; i < len; ++i)
|
|
{
|
|
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];
|
|
}
|
|
}
|