由于工作需要,要用.net的程序调用一个java编写的web service接口,接口的一个参数要求md5方式加密。
.net中的md5加密是很容易的,采用msdn中给出的方法:
// Hash an input string and return the hash as
// a 32 character hexadecimal string.
static string getMd5Hash(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
可是,当输入的字符串是中文的时候,问题出现了,加密出来的字符串不一样:
输入工作
java8c87df93416ebdf251bcb6b328ec3c3b
.net12e709e3a9a82b441b739a5c8ba035de
首先想到的是对中文的编码方式不一样,可是无论用utf8还是unicode结果都不同。
用google搜索 “java MD5 算法”找到的一篇文章解释了我的疑惑
http://blog.csdn.net/Peter_K/archive/2007/03/13/1527629.aspx
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
在.net中用同样的方式
private string getMd5Hash(string input)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
char[] temp = input.ToCharArray();