2016-01-27 196 views
1

我需要使用种子:1 2 3 6和明文密码学来实现Rc4算法。我遵循了我们在课堂上提供的这个指导原则,但它并没有正确初始化S。 enter image description here实现Rc4算法

我的输出是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; 






} 

回答

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指令。 (但是在初始化时要小心,因为如果iunsigned chari<256将始终为真。)