将十六进制字符串转换为Crypto++中的字节

Convert Hex string to bytes in Crypto++

本文关键字:字节 Crypto++ 十六进制 字符串 转换      更新时间:2023-10-16

我有一个十六进制字符串,需要将其转换为const byte*。我正在使用Crypto++进行哈希,它需要密钥在const byte*中。有什么方法可以使用任何Crypto++库将十六进制字符串转换为const byte*吗?或者我必须自己想出吗?

Crypto++中有一个HexDecoder类。

您需要为这些字符添加内容。Crypto++似乎没有直接区分字符和字节。因此varren提供的以下代码行将起作用:

string destination;
StringSource ss(source, true, new HexDecoder(new StringSink(destination)));    
const byte* result = (const byte*) destination.data();

我有一个十六进制字符串,需要将其转换为常量字节*

但它将是一串。我需要它在字节*中

那么您应该使用HexCoder和ArraySink。类似于:

string encoded = "FFEEDDCCBBAA99887766554433221100";
ASSERT(encoded.length() % 2 == 0);
size_t length = encoded.length() / 2;
unique_ptr<byte[]> decoded(new byte[length]);
StringSource ss(encoded, true /*pumpAll*/, new ArraySink(decoded.get(), length));

然后可以将字节数组decoded.get()用作byte*

您也可以使用vector<byte>。在这种情况下,byte*&v[0]。类似于:

string encoded = "FFEEDDCCBBAA99887766554433221100";
ASSERT(encoded.length() % 2 == 0);
size_t length = encoded.length() / 2;
vector<byte> decoded;
decoded.resize(length);
StringSource ss(encoded, true /*pumpAll*/, new ArraySink(&decoded[0], length));

(评论)但它将是字符串。我需要它在字节*中

这更容易:

string encoded = "FFEEDDCCBBAA99887766554433221100";
string decoded;
StringSource ss(encoded, true /*pumpAll*/, new StringSink(decoded));
const byte* data = reinterpret_cast<const byte*>(decoded.data());

如果你想要非常量版本,那么使用:

byte* ptr = reinterpret_cast<byte*>(&decoded[0]);
// HEX to BIN using CryptoPP
string encoded = "FFEEDDCCBBAA99887766554433221100";
size_t length = encoded.length() / 2;
vector<byte> decoded;
decoded.resize(length);
StringSource ss(encoded, true, new HexDecoder(new ArraySink(&decoded[0], length)));