【问题标题】:Implementing Rc4 algorithm实现 Rc4 算法
【发布时间】:2016-01-27 21:56:33
【问题描述】:

我需要实现一个带有种子的 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;






}

【问题讨论】:

    标签: encryption cryptography rc4-cipher


    【解决方案1】:

    实际上,我认为您正确生成了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 值而不是ints 变得更加整洁。这将消除到处乱扔的% 256 指令。 (但在初始化时要小心,因为如果iunsigned chari&lt;256 将始终为真。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2016-11-06
      • 2020-05-18
      相关资源
      最近更新 更多