我正在编写一个可以使用密码RC4加密文件的程序,在我的文件"test.txt“中是一个单词”明文“,该程序也应该加密并保存在一个文件中(为了测试,我使用了"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;
}我的关键是:“关键”,结果应该是

发布于 2021-11-16 12:07:24
你的算法在数学上是完全正确的,我只是对你的代码的其他部分做了一些小的修正,你的代码得到了正确的输出。
为了测试目的,让我们以测试示例从维基来的为例,第一个示例。输入键将是Key,输入文件将是Plaintext,结果文件应该是BB F3 16 E8 D9 40 AF 0A D3中的十六进制。修改后的代码通过了此测试。
在下面的代码中,您从控制台输入一个键,然后从tekst.txt获取输入文件,并将输出文件写入Encryption_tekst.txt。最好不要以ASCII字符的形式将结果打印到控制台,而是在十六进制查看器中查看结果文件,因为控制台将与字符编码混淆,最好以十六进制方式查看。
我在控制台中添加了打印结果的十六进制字符。还注意到,在下面的代码中,第一个块将Plaintext写到tekst.txt中,我这样做是为了举例,这样代码就可以被复制、粘贴和运行,而不需要任何额外的依赖关系。您必须删除写入teks.txt的第一个块,因为您有自己的输入tekst.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使用代码页Encryption_tekst.txt在十六进制查看器中查看的输出CP1252

https://stackoverflow.com/questions/69981676
复制相似问题