构造一个包含二进制数组的十六进制值的字符串

Construct a string who contain the hexValue of a binary array

本文关键字:数组 二进制 十六进制 字符串 包含 一个      更新时间:2023-10-16

我正在尝试从字节数组(libcrypto++)构造一个字符串,但我在"0"上遇到了问题,以便连接到c ++中的SQS

结果几乎是正确的,除了字符串末尾的一些"0"去。

std::string shaDigest(const std::string &key = "") {    
        byte out[64] = {0};
        CryptoPP::SHA256().CalculateDigest(out, reinterpret_cast<const byte*>(key.c_str()), key.size());
        std::stringstream ss;
        std::string rep;
        for (int i  = 0; i < 64; i++) {
            ss << std::hex << static_cast<int>(out[i]);
        }
        ss >> rep;
        rep.erase(rep.begin()+64, rep.end());
        return rep;
    }

输出:

correct : c46268185ea2227958f810a84dce4ade54abc4f42a03153ef720150a40e2e07b
mine    : c46268185ea2227958f810a84dce4ade54abc4f42a3153ef72015a40e2e07b00
                                                    ^          ^

编辑:我正在尝试做与python中的hashlib.sha256('').hexdigest()相同的操作。

如果这确实有效,这里是包含我的建议的解决方案。

std::string shaDigest(const std::string &key = "") {    
    std::array<byte, 64> out {};
    CryptoPP::SHA256().CalculateDigest(out.data(), reinterpret_cast<const byte*>(key.c_str()), key.size());
    std::stringstream ss;
    ss << std::hex << std::setfill('0');
    for (byte b : out) {
        ss << std::setw(2) << static_cast<int>(b);
    }
    // I don't think `.substr(0,64)` is needed here;
    // hex ASCII form of 64-byte array should always have 128 characters
    return ss.str(); 
}

您可以正确转换十六进制的字节,一旦字节值大于 15,它就会正常工作。但在下面,第一个六位数字是 0,默认情况下不打印。两个缺席的 0 分别表示 0x03 -> 30x0a -> a

您应该使用 :

    for (int i  = 0; i < 64; i++) {
        ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(out[i]);
    }

您需要设置整数的宽度,以便使用少于两个十六进制数字的数字进行适当的零填充。请注意,您需要在插入到流中的每个数字之前重新设置宽度。

例:

#include <iostream>
#include <iomanip>
int main() {
    std::cout << std::hex << std::setfill('0');
    for (int i=0; i<0x11; i++) 
        std::cout << std::setw(2) << i << "n";
}

输出:

$ g++ test.cc && ./a.out
00
01
02
03
04
05
06
07
08
09
0a
0b
0c
0d
0e
0f
10

供参考:

  • http://en.cppreference.com/w/cpp/io/manip/setw
  • http://en.cppreference.com/w/cpp/io/manip/setfill