将十六进制字符串转换为二进制数据MD5 [英] Convert hex string to binary data MD5

查看:244
本文介绍了将十六进制字符串转换为二进制数据MD5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!
我正在制作MD5应用程序以对数据库中的密码进行哈希处理.
我已将密码成功地哈希到表中的Pwd_hash列中,该列的数据类型为char(32).
但是,我在一些论坛中看到,最好将哈希值保留在binary(16)列中.
现在,我的问题是如何将十六进制字符串转换为二进制值?

作为一个小例子:

Hello!
I am making an MD5 application to hash the passwords in my database.
I successfully hashed the passwords into a Pwd_hash column in my table and it is of datatype char(32).
However, I have seen in some forums that it is best to keep the hash value in a binary(16) column.
Now, my problem is how do I convert the hex string to a binary value?

As a little example:

#include <iostream>
#include <string>
#include <bitset>
using namespace std;


int main()
{
	for(short int c = 0x1; c <= 0x3; c++)
	{
        bitset<((sizeof(short int) / 2 ) * 8)/2> binary(c); //sizeof() returns bytes, not bits!
        //cout << "Letter: " << c << "\t";
        cout << "Hex: " << hex << c << "\t";
        cout << "Binary: " << binary << endl;	
    }
	return 0;
}


</bitset></string></iostream>



但是,返回的二进制值是一个4字节的值,其中每个元素占用1个字节.
我想要的是十六进制字符串中的每对字符,它将转换为相应的二进制值.
例如0x82将变为二进制(1000 0010),而不是"1000 0010".后者意味着8个字节,而不是1个字节.
我希望我能使自己清楚...



However, the binary value returned is a 4-byte value, where each element takes up 1 byte.
What I want is for each pair of characters in the hex string, it is converted to the corresponding binary value.
e.g 0x82 will become binary(1000 0010) and not "1000 0010". The latter would imply 8 bytes and not 1 byte.
I hope I am making myself clear...

推荐答案

您必须一次转换两个十六进制字符,例如
You have to convert two hexadecimal characters at time, e.g.
string s = "ed07";
vector <unsigned char> binary;
for (string::size_type i=0; i<s.length(); i+=2)
{
  unsigned char b = (unsigned char) strtoul(s.substr(i,2).c_str(), NULL, 16);
  binary.push_back(b);
}


这篇关于将十六进制字符串转换为二进制数据MD5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆