我有一个包含十六进制值的字节数组。为了存储它我将其编码为字符串,并首先检索它我将其解码为字符串,如何将其转换为字节数组呢?
以下是代码:
我在这里创建字节数组:
AutoSeededRandomPool prng;
byte key[CryptoPP::AES::MAX_KEYLENGTH];
prng.GenerateBlock(key, sizeof(key));
然后将其编码为字符串,如下所示:
string encoded;
encoded.clear();
StringSource(key, sizeof(key), true,
new HexEncoder(
new StringSink(encoded)
) // HexEncoder
); // StringSource
现在要获取主字节数组,首先我解码它:
string decodedkey;
StringSource ssk(encoded, true /*pumpAll*/,
new HexDecoder(
new StringSink(decodedkey)
) // HexDecoder
); // StringSource
但我不知道如何到达字节数组。
byte key[CryptoPP::AES::MAX_KEYLENGTH];
答案 0 :(得分:0)
我认为这对你的编码更有效。假设byte
是unsigned char
的typedef。
std::stringstream ss;
ss.fill('0');
ss.width(2);
for (int x = 0; x < CryptoPP::AES::MAX_KEYLENGTH; x++)
{
unsigned int val = (unsigned int)bytes[x];
ss << std::hex << val; // writes val out as a 2-digit hex char
}
std::string result = ss.str(); // result is a hex string of your byte array
以上内容会将{1,99,200}
等字节数组转换为"0163C8"
然后将字符串解码回字节数组:
byte key[MAX_KEYLENGTH] = {};
for (int x = 0; x < MAX_KEYLENGTH; x++)
{
char sz[3];
sz[0] = result[x*2];
sz[1] = result[x*2+1];
sz[2] = '\0';
unsigned char val = (unsigned char)strtoul(sz, NULL, 10);
bytes[x] = val;
}
答案 1 :(得分:0)
key = (byte *)decodedkey.data();