我实现了一种相当简单的方法来加密和解密字符串到文件,然后再返回。 我使用的方法如下:
string encrypt(string msg, string key) {
string tmp(key);
while (key.size() < msg.size()) key += tmp;
for (std::string::size_type i = 0; i < msg.size(); ++i) msg[i] ^= key[i];
return msg;
}
string decrypt(string msg, string key) {
return encrypt(msg, key);
}
但是我使用的一些键并不是很有用。该字符串被正确加密并写入文件。但是,当我尝试解密所有内容(将文件加载到字符串中,解密它,写入回另一个文件)时,新文件明显较小,并且不包含存储在其中的全部信息。
到目前为止我尝试过的键是:
string crypt = "abc"; //works kinda well
string crypt = "_H84M!-juJHFXGT01X1*G6a$gEv"; //doesnt work
string crypt = "H84MjuJHFXGT01X1G6agEv"; //doesnt work either
我希望您能帮助我并就如何选择可用的 key 提供任何建议。
文件处理代码:
ofstream temp;
temp.open("temp", ios::in | ios::trunc);
temp << encrypt(buffer, crypt);
temp.close();
ifstream in(file);
string content((std::istreambuf_iterator<char>(in)) (std::istreambuf_iterator<char>()));
ofstream plain;
plain.open(newfile, ios::in | ios::trunc);
plain << decrypt(content, crypt);
plain.close();
最佳答案
由于您的加密字符串中有二进制数据,因此您应该使用未格式化的 write
方法而不是 operator<<
:
ofstream os(...);
std::string encrypted = ...;
os.write( encrypted.data(), encrypted.size() );
请注意,如果文件中需要多个加密字符串,您可能需要在实际数据之前写入数据大小。然后你用 istream::read()
读取数据大小和数据:
void write( std::ostream &out, const std::string &encrypted )
{
size_t length = encrypted.size();
of.write( &length, sizeof( length ) );
of.write( encryped.data(), length );
}
std::string read( std::istream &in )
{
size_t length = 0;
in.read( &length, sizeof( length ) );
std::string str( length );
in.read( &str[0], length );
return str;
}
注释 2:将加密数据存储在 std::vector<char>
中可能是个好主意而不是std::string
,这将防止许多问题 - 您将无法使用许多隐式假定字符串以 null 结尾的函数。
关于c++ - 使用 C++ 进行异或加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39298087/