Convert Hex string to bytes in Crypto++

2019-02-18 21:31发布

I have string of hexadecimals which I need to convert to const byte*. I am using Crypto++ to do hashing and it needs the key to be in const byte* Is there any way i can convert the string of hexadecimal into const byte* using any of the Crypto++ libs or must i need to come up with my own?

2条回答
虎瘦雄心在
2楼-- · 2019-02-18 22:13

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();
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-18 22:32

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]);
查看更多
登录 后发表回答