我正在写一个程序,可以使用密码 RC4 加密文件,在我的文件“test.txt”是一个词“Plaintext”,程序应该加密并保存在一个文件中(测试我使用“cout”)
我觉得代码的最后一部分有问题
while ( plik.read(&x,1) )
{
i = ( i + 1 ) % 256;
j = ( j + S [ i ] ) % 256;
swap( S [ i ], S [ j ] );
temp = S [ ( S [ i ] + S [ j ] ) % 256 ] ^ x;
cout << temp;
}
没有错误,没有警告,我应该改变什么?
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned char S[256];
int i = 0;
for ( i = 0; i < 256; i++ )
S [ i ] = i;
string Key;
cout << "Enter the key: ";
cin >> Key;
int j = 0;
for ( i = 0; i < 256; i++ )
{
j = ( j + S [ i ] + Key.at( i % Key.length() ) ) % 256;
swap( S [ i ], S [ j ] );
}
ifstream plik;
string path = "tekst.txt";
plik.open( path );
char tekst;
plik >> tekst;
string printFile = "Encryption_" + path;
ofstream outfile( printFile );
char x;
j = 0;
i = 0;
string temp;
while ( plik.read(&x,1) )
{
i = ( i + 1 ) % 256;
j = ( j + S [ i ] ) % 256;
swap( S [ i ], S [ j ] );
temp = S [ ( S [ i ] + S [ j ] ) % 256 ] ^ x;
cout << temp;
}
plik.close();
outfile.close();
return 0;
}
我的关键是:“关键”,结果应该是
Good Result你的算法在数学上是完全正确的,我只是对你的代码的其他部分做了一些小的更正,你的代码做出了正确的输出。
出于测试目的,让我们以测试示例here from Wiki为例,第一个示例。输入键将是Key
,输入文件将是Plaintext
,生成的文件应该是十六进制的BB F3 16 E8 D9 40 AF 0A D3
。以下修改后的代码通过了此测试。
在的代码中,您从控制台输入一个键,然后从tekst.txt
获取输入文件,并将输出文件写入Encryption_tekst.txt
。最好不要将结果作为 ASCII 字符打印到控制台,而是在十六进制查看器中查看结果文件,因为控制台会弄乱字符编码,最好以十六进制查看。
我在控制台添加了打印结果十六进制字符。另外注意在的代码中,第一个块将Plaintext
写入tekst.txt
,我这样做是为了示例的目的,以便代码可以复制粘贴并运行,而没有任何额外的依赖关系。您必须删除写入teks.txt
的第一个块,因为您有自己的输入它
运行以下示例时,在控制台提示符下输入Key
。
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdint>
using namespace std;
int main() {
{
ofstream out("tekst.txt");
out << "Plaintext";
}
unsigned char S[256];
int i = 0;
for (i = 0; i < 256; i++)
S[i] = i;
string Key;
cout << "Enter the key: ";
cin >> Key;
int j = 0;
for (i = 0; i < 256; i++) {
j = (j + S[i] + Key.at(i % Key.length())) % 256;
swap(S[i], S[j]);
}
ifstream plik;
string path = "tekst.txt";
plik.open(path);
string printFile = "Encryption_" + path;
ofstream outfile(printFile);
char x;
j = 0;
i = 0;
char temp = 0;
while (plik.read(&x, 1)) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
swap(S[i], S[j]);
temp = S[(S[i] + S[j]) % 256] ^ x;
outfile << temp;
cout << std::hex << std::setw(2) << std::setfill('0')
<< uint32_t(uint8_t(temp)) << " ";
}
plik.close();
outfile.close();
return 0;
}
输入键 (从控制台):
Key
输入文件tekst.txt
:
Plaintext
控制台输出:
Enter the key: Key
bb f3 16 e8 d9 40 af 0a d3
在带有代码页CP1252
的十六进制查看器中查看的输出Encryption_tekst.txt
:
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(48条)