我正在实现一个使用 RC4 流密码进行加密和解密的自定义 iostream(即,具有读取、写入、查找和关闭功能)。该流的一个约定是它是双向的,调用代码需要能够在进行任何实际读取或写入之前任意寻找到流中的任何位置。
现在因为 RC4 使用的密钥依赖于所有先前的交换操作,直到给定的“告诉”位置,我如何才能结合任意寻找任何位置的能力?
显然,在执行实际的异或转换过程之前,我可以查找到给定查找偏移的位置(在以下示例中由THIS BIT标记),例如:
/**
* @brief called from a stream's read or write function
* @param in the input buffer
* @param out the output buffer
* @param startPosition the current stream position (obtained via the streams
* tellg or tellp functions for read and write respectively)
* @param length the number of bytes to transform
*/
void transform(char *in, char *out,
std::ios_base::streamoff startPosition,
long length)
{
// need to reset sbox from member s_box each time this
// function is called
long sbox[256];
for (int i = 0; i<256; ++i) {
sbox[i]=m_sbox[i];
}
// ***THIS BIT***
// need to run the swap operation startPosition times
// to get sbox integer sequence in order
int i = 0, j = 0, k = 0;
for (int a=0; a < startPosition; ++a) {
i = (i + 1) % 256;
j = (j + sbox[i]) % 256;
swapints(sbox, i, j);
}
// now do the actual xoring process up to the length
// of how many bytes are being read or written
for (int a=0; a < length; ++a) {
i = (i + 1) % 256;
j = (j + sbox[i]) % 256;
swapints(sbox, i, j);
k = sbox[(sbox[i] + sbox[j]) % 256];
out[a] = in[a] ^ k;
}
}
然后将从流实现的读取或写入中调用转换,例如:
MyStream&
MyStream::read(char * const buf, std::streamsize const n)
{
std::ios_base::streamoff start = m_stream.tellg();
std::vector<char> in;
in.resize(n);
(void)m_stream.read(&in.front(), n);
m_byteTransformer->transform(&in.front(), buf, start, n);
return *this;
}
编辑:流应该不知道转换函数是如何工作的。转换功能是完全独立的,我应该能够在不同的转换实现中自由交换。
编辑:函数 swapints 看起来像这样:
void swapints(long *array, long ndx1, long ndx2)
{
int temp = array[ndx1];
array[ndx1] = array[ndx2];
array[ndx2] = temp;
}
上述变换函数的真正问题在于它的速度很慢,因为它必须在执行异或变换之前执行 startPosition 初始交换操作。当执行许多查找操作时,这是非常有问题的。现在我听说 RC4 是为了快速,但我的(可能是糟糕的实现)建议在初始交换操作集的情况下使用其他方式。
所以我真正的问题是:如何优化上述代码以减少所需操作的数量?理想情况下,我想消除交换操作的初始(“ THIS BIT ”)集
编辑:优化初始 sbox 设置可能是微不足道的(例如,使用 egur 建议的 memcpy)。我认为重要的优化是如何优化THIS BIT标记的循环。也许所有这些交换整数都可以更简洁地编程,而无需 for 循环。
谢谢,
本