最近与东信北邮的联调超炫接口,在这个接口中需要使用MD5算来相互验证用户身份,对方使用JAVA开发我方使用.NET开发,遗憾的是对方的MD5算法与RFC 1321的Test siute不相符。他们提供了MD5算法,经过多次查找资料并询问想关人员,终于实现了一致性,特将代码奉上以备与我有类似问题的人参考:
1、Java版
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/*
*
* 生成32位MD5消息摘要
*
* @param info
* String 消息原文
* @return
*/
public static String getDigestStr(String info) {
try {
byte [] res = info.getBytes();
MessageDigest md = MessageDigest.getInstance( " MD5 " );
byte [] result = md.digest(res);
for ( int i = 0 ; i < result.length; i ++ ) {
md.update(result[i]);
}
byte [] hash = md.digest();
StringBuffer d = new StringBuffer( "" );
for ( int i = 0 ; i < hash.length; i ++ ) {
int v = hash[i] & 0xFF ;
if (v < 16 ) {
d.append( " 0 " );
}
d.append(Integer.toString(v, 16 ).toUpperCase());
}
return d.toString();
} catch (Exception e) {
return null ;
}
}
* 生成32位MD5消息摘要
*
* @param info
* String 消息原文
* @return
*/
public static String getDigestStr(String info) {
try {
byte [] res = info.getBytes();
MessageDigest md = MessageDigest.getInstance( " MD5 " );
byte [] result = md.digest(res);
for ( int i = 0 ; i < result.length; i ++ ) {
md.update(result[i]);
}
byte [] hash = md.digest();
StringBuffer d = new StringBuffer( "" );
for ( int i = 0 ; i < hash.length; i ++ ) {
int v = hash[i] & 0xFF ;
if (v < 16 ) {
d.append( " 0 " );
}
d.append(Integer.toString(v, 16 ).toUpperCase());
}
return d.toString();
} catch (Exception e) {
return null ;
}
}
2、.Net版
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
///
<summary>
/// 对应Java版的MD5(连续计算两次摘要)
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static String GetDigestStr(String info)
{
try
{
byte [] res = System.Text.Encoding.Default.GetBytes(info);
MD5CryptoServiceProvider md = new MD5CryptoServiceProvider();
byte [] result = md.ComputeHash(res);
byte [] hash = md.ComputeHash(result);
StringBuilder sbuilder = new StringBuilder();
for ( int i = 0 ; i < hash.Length; i ++ )
{
int v = hash[i] & 0xFF ;
if (v < 16 ) sbuilder.Append( " 0 " );
sbuilder.Append(Convert.ToString(v, 16 ).ToUpper());
}
return sbuilder.ToString();
}
catch
{
return null ;
}
}
/// 对应Java版的MD5(连续计算两次摘要)
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static String GetDigestStr(String info)
{
try
{
byte [] res = System.Text.Encoding.Default.GetBytes(info);
MD5CryptoServiceProvider md = new MD5CryptoServiceProvider();
byte [] result = md.ComputeHash(res);
byte [] hash = md.ComputeHash(result);
StringBuilder sbuilder = new StringBuilder();
for ( int i = 0 ; i < hash.Length; i ++ )
{
int v = hash[i] & 0xFF ;
if (v < 16 ) sbuilder.Append( " 0 " );
sbuilder.Append(Convert.ToString(v, 16 ).ToUpper());
}
return sbuilder.ToString();
}
catch
{
return null ;
}
}