c++ - 如何读取密文的所有十六进制值?
问题描述
有一个没有任何扩展名的密文,大小为 32 字节。因此,我可以用十六进制编辑器得到它的十六进制值,它的十六进制值是;
a3 0b 35 8f 14 4e fe 5e 27 5a bd 8c 53 8b a0 cb ae da d3 fc 87 8b 51 0b d6 37 3e 91 86 9f f3 c9
我试图用我的代码从密文中读取这些值,
ifstream stream;
unsigned char c;
char arr[2];
char cipherhex[65];
int i=0;
stream.open("ciphertext2");
while (!stream.eof()) {
stream >> c;
sprintf(arr, "%02x", c);
cout << arr[0] << arr[1] << " ";
cipherhex[i] = arr[0];
cipherhex[i+1] = arr[1];
i += 2;
}
但是,当我运行这段代码时,虽然有0x类十六进制值的条件,但它可以读取这些十六进制值;
a3 35 8f 14 4e fe 5e 27 5a bd 8c 53 8b a0 cb ae da d3 fc 87 8b 51 d6 37 3e 91 86 9f f3 c9 c9
该代码不能读取0b、09、0c,但对于不同的密文它可以读取03或0e。我无法理解它如何读取03和0e但不能读取09或0b。提前致谢。
一般来说,读取十六进制值没有问题,但是读取我上面提到的特定值有问题。
解决方案
您的代码中有几个错误:
不以二进制模式打开文件。
用于
operator>>
读取格式化字符,忽略空白字符。没有为 分配足够的内存
arr[]
,导致 中的缓冲区溢出sprintf()
。cipherhex
读取完成后不以空值终止(可选)。
试试这个:
ifstream stream;
char c, arr[3], cipherhex[65];
int cypherhexlen = 0;
stream.open("ciphertext2");
while ((cypherhexlen < 64) && stream.get(c)) {
sprintf(arr, "%02x", static_cast<unsigned char>(c));
cout << arr[0] << arr[1] << " ";
cipherhex[cypherhexlen] = arr[0];
cipherhex[cypherhexlen+1] = arr[1];
cypherhexlen += 2;
}
cipherhex[cypherhexlen] = '\0';
// use cipherhex as needed...
或者,我会选择更像这样的东西:
ifstream stream;
unsigned char cipher[32];
stream.open("ciphertext2");
stream.read(reinterpret_cast<char*>(cipher), 32);
int cypherlen = stream.gcount();
for(int i = 0; i < cypherlen; ++i) {
cout << hex << noshowbase << setw(2) << cipher[i] << " ";
}
// use cipher as needed...
推荐阅读
- java - Android 最可靠的数据压缩算法是什么?
- sql-server - 如何在 SQL Server 中编写触发器主体
- java - 您可以混合使用抽象数据类型吗?例如地图的优先队列?
- php - 另一个 PHP 中的 PHP
- laravel-dusk - Laravel 8 Dusk:使用 Jetstream 和 Inertia JS 测试登录不起作用
- php - Apache2 RewriteRule 在图像 docker.io/library/php:7.4-apache 的容器中不起作用
- kubernetes - Prometheus Operator:无法访问 Prometheus 实例
- ios - 从核心数据中关闭 Swift 或 Objective-C 中的模态视图控制器后重绘 VC
- python - 是否有 pandas 函数通过多值比较过滤 DataFrame?
- select - 直接回答 sparql 选择 graphdb 等效类的查询?