当到达空字节时,C++XOR失败

C++ XOR failing when reaching null byte?

本文关键字:C++XOR 失败 字节      更新时间:2023-10-16

这是我现在拥有的代码:

#include <iostream>
#include <string>
#include <sstream>
std::string string_to_hex(const std::string& input)
{
    static const char* const lut = "0123456789ABCDEF";
    size_t len = input.length();
    std::string output;
    output.reserve(2 * len);
    for (size_t i = 0; i < len; ++i)
    {
        const unsigned char c = input[i];
        output.push_back(lut[c >> 4]);
        output.push_back(lut[c & 15]);
    }
    return output;
}
std::string encrypt(std::string msg, std::string key)
{
    // Make sure the key is at least as long as the message
    std::string tmp(key);
    while (key.size() < msg.size())
        key += tmp;
    // And now for the encryption part
    for (std::string::size_type i = 0; i < msg.size(); ++i)
        msg[i] ^= key[i];
    return msg;
}
std::string decrypt(std::string msg, std::string key)
{
    return encrypt(msg, key); // lol
}
int main()
{
    std::cout << string_to_hex(encrypt("Hello World!", "monkey")) << std::endl;
    std::cout << decrypt("x25x0Ax02x07x0Ax59x3Ax00x1Cx07x01x58", "monkey") << std::endl;
    std::cout << string_to_hex(encrypt("Hello. This is a test of encrypting strings in C++.", "monkey")) << std::endl;
    std::cout << decrypt("x25x0Ax02x07x0Ax57x4Dx3Bx06x02x16x59x04x1Cx4Ex0Ax45x0Dx08x1Cx1Ax4Bx0Ax1Fx4Dx0Ax00x08x17x00x1Dx1Bx07x05x02x59x1Ex1Bx1Cx02x0Bx1Ex1Ex4Fx07x05x45x3Ax46x44x40", "monkey") << std::endl;
}

输出如下:

250A02070A593A001C070158
Hello W
250A02070A574D3B06021659041C4E0A450D081C1A4B0A1F4D0A000817001D1B070502591E1B1C020B1E1E4F0705453A464440
Hello. This is a test of e

解密似乎在到达\x00时停止。有人对如何解决这个问题有什么想法吗?

谢谢!

接收char*的std::string构造函数假设输入是一个以null结尾的字符串,因此即使字符串文本中有大量数据超过了null字节,当您将其传递到函数中时,std::字符串构造函数将在它到达该null字节时立即停止读取。

你有几个选择来解决这个问题。作为一种选择,std::string类型有一个双参数构造函数,您可以在其中提供一个指针,指向字符串中的第一个元素和字符串结束字节之后的元素。然后,std::字符串将自己初始化为该范围内的文本,忽略中间的null终止符。

char s1[] = "x25x0Ax02x07x0Ax59x3Ax00x1Cx07x01x58";
char s2[] = "x25x0Ax02x07x0Ax57x4Dx3Bx06x02x16x59x04x1Cx4Ex0Ax45x0Dx08x1Cx1Ax4Bx0Ax1Fx4Dx0Ax00x08x17x00x1Dx1Bx07x05x02x59x1Ex1Bx1Cx02x0Bx1Ex1Ex4Fx07x05x45x3Ax46x44x40";
std::cout << string_to_hex(encrypt("Hello World!", "monkey")) << std::endl;
std::cout << decrypt(std::string(std::begin(s1), std::end(s1)-1), "monkey") << std::endl;
std::cout << string_to_hex(encrypt("Hello. This is a test of encrypting strings in C++.", "monkey")) << std::endl;
std::cout << decrypt(std::string(std::begin(s2), std::end(s2)-1), "monkey") << std::endl;

演示。