Convert Hex string to bytes in Crypto++

时光毁灭记忆、已成空白 提交于 2019-12-01 09:11:50
Maarten Bodewes

There is a HexDecoder class in Crypto++.

You need to feed this characters. It seems that Crypto++ does not directly distinguish between characters and bytes. So the following line of code supplied by varren will work:

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

I have string of hexadecimals which I need to convert to const byte*
...
But it will be in string. I need it to be in byte*

You should use a HexDecoder and ArraySink then. Something like:

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));

You can then use the byte array decoded.get() as a byte*.

You can also use a vector<byte>. In this case, the byte* is &v[0]. Something like:

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));

(comment) But it will be in string. I need it to be in byte*

This is even easier:

string encoded = "FFEEDDCCBBAA99887766554433221100";
string decoded;

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

If you want the non-const version then use:

byte* ptr = reinterpret_cast<byte*>(&decoded[0]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!