gpt4 book ai didi

c++ - 我加密但无法使用 C++ 执行文件解码

转载 作者:行者123 更新时间:2023-11-28 00:57:01 25 4
gpt4 key购买 nike

编写一个与我的加密程序类似的加密程序:• 提示用户输入 key 并使用它来计算随机数生成器的种子• 提示用户给出输入文件的名称和输出编码/解码文件 • 使用从用户 key 获得的种子从随机数生成器创建随机字节序列。 • 使用随机位 r 对位 x 进行编码,如下所示: x⊕ = r • 由于∀r ∈{0,1},r ⊕r = 0,使用相同的随机字节序列和相同的操作 x 执行解码⊕ = r 。解码基于操作 x⊕r ⊕r = x⊕(r ⊕r) = x⊕0 = x

下面是用于加密的代码,但在解密时,密文仅包含 3 个字符。我无法弄清楚为什么解码不起作用。我正在使用 Dev-C++。非常感谢您的帮助。

  #include<iostream>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<fstream>

using namespace std;


int main()
{
char n, line[1024], keystring[100]; char FitoEncr[100], NewFiCrypt[100];
char FiletobeDecrypted[100];
ifstream IS ("FitoEncr.txt", ios::in);
ofstream OS ("NewFiCrypt.txt", ios::out);

unsigned int psswd=0, number;
cout<<"Please, enter a secret key :";
cin.getline(keystring, 100);
for( int i=0;keystring[i]!='\0'; i++)

psswd=(psswd+3)*keystring[i];
cout<<"initial password: "<<keystring<<endl;
cout<<"encrypted password: "<<psswd<<endl;

cout<<"please, enter the name of the input file: ";
cin.getline(FitoEncr,20);
cout<<"please, enter the name of the output file: ";
cin.getline(NewFiCrypt,20);

srand(psswd); //not sure about creating the sequence of random bytes from a...
number=rand() % 255; //random number generator with the seed obtained from user's secret key

//ENCRYPTION

while(IS.get(n))
{
if(IS.get(n))
{
n^=rand();
OS<<n;
cout<<"character coded:"<<n;
}

}
IS.close();
OS.close();

//DECRYPTION

ifstream IS1;
ofstream OS1;

IS1.open("NewFiCrypt.txt", ios::in);
OS1.open("FilDecr.txt", ios::out);

while(IS1.get(n))
{
if(IS1.get(n))
{
n^=rand(); //I think the problem starts on this line...
OS1<<n;
cout<<"character coded:"<<n;
}

}
IS1.close();
OS1.close();

getch();

return 0;
}

最佳答案

您在加密之前为随机数生成器播种,但在解密之前没有播种,因此随机数系列会有所不同;显然,它们必须相同才能起作用。如果再添加一个

srand(psswd);  

在解密之前,这会让你更接近。

不过,仔细检查后,还有一些其他重要问题。例如,每次调用 get(n) 时,您都会使用输入文件中的一个字符。您在 while 循环条件中调用 get(n),但随后立即在 if 中再次调用它;这意味着您将有效地跳过输入和输出中的所有其他字符;解密后的文件最终只会包含原始文件中 25% 的字符!只需完全删除 if 语句,您的循环就会正确。希望解决了这两个问题后,您的程序就能正常工作。

关于c++ - 我加密但无法使用 C++ 执行文件解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10532966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com