c++ - 使用 C++ 进行异或加密

标签 c++ encryption xor

我实现了一种相当简单的方法来加密和解密字符串到文件,然后再返回。 我使用的方法如下:

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/

相关文章:

encryption - AES、密码 block 链接模式、静态初始化向量和更改数据

ios - 在 iOS 中播放加密的 mp3

javascript - JS 和 Python 中 ^ 运算符的区别

c - 加密一个简单的数组

c++ - 为什么在从 dll 内部调整 vector 大小时会出现堆损坏?

c++ - 不间断地从循环中删除列表中的元素

encryption - 如何在 gatsby-config.js 中使用 AWS Amplify 环境变量?

python - Keras 矩阵乘法以获得预测值

具有相同名称的 C++ 包装器?

c++ - 如何使用 Item Delegate 检测 QListView <-> QAbstractListModel 中的行选择?