Convert Hex string to bytes in Crypto++

两盒软妹~` 提交于 2019-12-19 09:54:32

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/17816312/convert-hex-string-to-bytes-in-crypto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!