gpt4 book ai didi

c++ - 简单加密不起作用

转载 作者:行者123 更新时间:2023-11-30 05:28:39 25 4
gpt4 key购买 nike

我正在使用我在网上找到的简单加密。基本上,我在一个文件中流式传输,检查该文件是否打开(如果没有,显示一条错误消息)并在加密信息时将每一行放入数组的每个元素中。之后,我将该加密信息流式传输到输出文件中。

但是,我的 output.txt 文件中什么也没有。如果您自行测试,加密工作正常。

这是我的代码:

#include <string>  
#include <fstream>
#include <sstream> // for ostringstream
#include <iostream>
#include <stdio.h>
#include <algorithm>

/* Credits to kylewbanks.com */
string encrypt (string content) {
char key[3] = {'K'}; //Any chars will work
string output = content;

for (int i = 0; i < content.size(); i++)
output[i] = content[i] ^ key[i % (sizeof(key) / sizeof(char))];

return output;
}

int main() {
string input, line;
string content[10000];
string encryptedContent[10000];

int counter = 0, innerChoice = 0, i, finalCounter;

cout << "\tPlease enter the file name to encrypt!\n";
cout << "\tType '0' to get back to the menu!\n";
cout << "Input >> ";

cin >> input;

/* Reads in the inputted file */
ifstream file(input.c_str());
//fopen, fscanf

if(file.is_open()) {

/* Counts number of lines in file */
while (getline(file, line)) {
counter++;
}

cout << counter;

finalCounter = counter;

for (i = 0; i < finalCounter; i++) {
file >> content[i];
encryptedContent[i] = encrypt(content[i]);
cout << encryptedContent[i];
}
} else {
cout << "\tUnable to open the file: " << input << "!\n";
}

/* Write encryption to file */
ofstream outputFile("output.txt");
for (i = 0; i < finalCounter ; i++) {
outputFile << encryptedContent;
}
outputFile.close();
}

知道哪里出了问题吗?

最佳答案

string content[10000];
string encryptedContent[10000];

这是错误的,因为它正在创建 20000 个字符串(您可能认为它正在创建一个足够大的字符数组来读取数据)。

string content; 就够了。它可以调整大小以处理任何长度的字符串。

你只需要读/写二进制文件:

int main() 
{
string input = "input.txt";
ifstream file(input, ios::binary);
if (!file.is_open())
{
cout << "\tUnable to open the file: " << input << "!\n";
return 0;
}

string plaintext;

//read the file
file.seekg(0, std::ios::end);
size_t size = (size_t)file.tellg();
file.seekg(0);
plaintext.resize(size, 0);
file.read(&plaintext[0], size);

cout << "reading:\n" << plaintext << "\n";

//encrypt the content
string encrypted = encrypt(plaintext);

//encrypt again so it goes back to original (for testing)
string decrypted = encrypt(encrypted);

cout << "testing:\n" << decrypted << "\n";

/* Write encryption to file */
ofstream outputFile("output.txt", ios::binary);
outputFile.write(encrypted.data(), encrypted.size());

return 0;
}

关于c++ - 简单加密不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36708754/

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