我需要实现一个种子的Rc4算法:1 2 3 6和纯文本密码学 . 我遵循我们在课堂上提供的这个准则,但它没有正确初始化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;
}
1 回答
实际上我认为你正确地生成
S[]
. 我只能假设're supposed to do something different with the key. (Perhaps'是一个ASCII字符串而不是四个字节值?检查您的作业说明 . )但是,稍后会出现问题 . 在流生成循环中,你应该do the increment and swap operations before you fetch a byte from S[] .