2016-01-27 192 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將始終爲真。)