实现Rc4算法

Implementing Rc4 algorithm

我需要使用种子 1 2 3 6 和纯文本密码学来实现 Rc4 算法。我遵循 class 中提供的指南,但它没有正确初始化 S。

我的输出是

并且需要

我的代码之前打印负值,不知道为什么,但我设法修复了这个错误。以为一切都很好,但事实并非如此。抱歉没有图片,我认为解释我的代码结构所遵循的内容更容易。我是 mod 4 种子,因为它包含 4 个字符,这可能是我的错误吗?

#include <iostream>
#include <string>
#include <string.h>


using std::endl;
using std::string;

void swap(unsigned int *x, unsigned int *y);



int main()
{
string plaintext = "cryptology";

char cipherText[256] = { ' ' };
unsigned int S[256] = { 0 };
unsigned int t[256] = { 0 };
unsigned int seed[4] = { 1, 2, 3, 6 };      // seed used for test case 1 
unsigned int temp = 0;
int runningTotal = 0;

unsigned int key = 0;



// inilializing s and t
for (int i = 0; i < 256; i++)
{

    S[i] = i;
    t[i] = seed[i % 4];
}

for (int i = 0; i < 256; i++)
{
    runningTotal += S[i] + t[i];
    runningTotal %= 256;
    swap(&S[runningTotal], &S[i]);

     std::cout  << S[i] <<" ";
}
runningTotal = 0;

for (int i = 0; i < plaintext.size(); i++)
{
    runningTotal %= 256;
    swap(&S[i], &S[runningTotal]);

    temp = (unsigned int)S[i] + (unsigned int)S[runningTotal];
    temp %= 256;

    key = S[temp];
    std::cout << endl;
    cipherText[i] = plaintext[i] ^ key;



}
std::cout << " this is cipher text " << endl;
std::cout << cipherText << endl;






system("pause");
return 0;
}
void swap(unsigned int *x, unsigned int *y)
{
unsigned int temp = 0;

temp = *x;
*x = *y;
*y = temp;






}

实际上,我认为您生成的 S[] 是正确的。我只能假设你应该用钥匙做一些不同的事情。 (也许它是一个 ASCII 字符串而不是四字节值?检查你的作业笔记。)

不过,后来出现了问题。在流生成循环中,你应该 do the increment and swap operations before you fetch a byte from S[].

for (int k = 0; k < plaintext.size(); k++)
{
   i = (i+1) % 256;                             // increment S[] index
   runningTotal = (runningTotal + S[i]) % 256;  // swap bytes
   swap(&S[i], &S[runningTotal]);

   temp = (S[i] + S[runningTotal]) % 256;       // fetch byte from S and
   cipherText[k] = plaintext[k] ^ S[temp];      // XOR with plaintext
}

NOTE: Although unrelated to your question, your code could be made a lot tidier by using unsigned char values instead of ints. That would eliminate the % 256 instructions that are littered all over the place. (But be careful during initialization, because i<256 will always be true if i is an unsigned char.)