java代码中md5加密与mysql直接加密结果不一致,java 和.net的MD5加密不一样?!

由于工作需要,要用.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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值