Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Hex string to bytes in Crypto++

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?

like image 305
M.A Avatar asked Oct 15 '25 04:10

M.A


2 Answers

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:

string destination;
StringSource ss(source, true, new HexDecoder(new StringSink(destination)));    
const byte* result = (const byte*) destination.data();
like image 184
Maarten Bodewes Avatar answered Oct 17 '25 00:10

Maarten Bodewes


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]);
like image 27
jww Avatar answered Oct 16 '25 23:10

jww



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!