实现Rc4算法

时间:2016-01-27 21:56:33

标签: encryption cryptography rc4-cipher

我需要实现一个种子的Rc4算法:1 2 3 6和纯文本密码学。我遵循我们在课堂上提供的这个指南,但它没有正确初始化S. enter image description here

我的输出是enter image description here

并且需要enter image description here

我的代码以前是打印负值,不知道为什么,但我设法修复了这个错误。认为一切都很好,但事实并非如此。对于这些图片感到抱歉,我认为我的代码结构更容易解释我的注意事项。我是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;






}

1 个答案:

答案 0 :(得分:2)

实际上我认为你正确地生成了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
}
  

注意:虽然与您的问题无关,但使用unsigned char值代替int s可以使您的代码更加整洁。这将消除遍布整个地方的% 256指令。 (但在初始化期间要小心,因为如果i<256iunsigned char将始终为真。)