当到达空字节时,C++XOR失败
C++ XOR failing when reaching null byte?
这是我现在拥有的代码:
#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;
演示。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 从父数组测试用例构造二叉树失败
- LibGit2 SSH身份验证失败
- 如何让LLDB在成功时退出,在失败时等待
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 使用模板化运算符重载 XOR 运算符失败
- 当到达空字节时,C++XOR失败