首页 文章

实现Rc4算法

提问于
浏览
1

我需要实现一个种子的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 回答

  • 2

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

    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,您的代码可以变得更加整洁 . 这将消除遍布整个地方的%256指令 . (但是在初始化期间要小心,因为如果我是无符号字符,i <256将始终为真 . )

相关问题