在.Net和Java中的MD5加密开发的一致性
1、C#.Net版
2、Java版
Code
/**//// <summary>
/// MD5加密
/// </summary>
/// <param name="s">字符串</param>
/// <param name="encoding">字符集编码</param>
/// <returns></returns>
public static String MD5(String s, Encoding encoding)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytValue = encoding.GetBytes(s);
byte[] bytHash = md5.ComputeHash(bytValue);
md5.Clear();
StringBuilder result = new StringBuilder();
for (int i = 0; i < bytHash.Length; i++)
{
result.Append(bytHash[i].ToString("x").PadLeft(2, '0'));
}
return result.ToString();
}
/**//// <summary>
/// MD5加密
/// </summary>
/// <param name="s">字符串</param>
/// <param name="encoding">字符集编码</param>
/// <returns></returns>
public static String MD5(String s, Encoding encoding)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytValue = encoding.GetBytes(s);
byte[] bytHash = md5.ComputeHash(bytValue);
md5.Clear();
StringBuilder result = new StringBuilder();
for (int i = 0; i < bytHash.Length; i++)
{
result.Append(bytHash[i].ToString("x").PadLeft(2, '0'));
}
return result.ToString();
}
2、Java版
Code
/** *//**
* MD5加密
* @param s 字符串
* @param charsetName 字符集名称
* @return
*/
public final static String MD5(String s, String charsetName)
{
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes(charsetName);
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
/** *//**
* MD5加密
* @param s 字符串
* @param charsetName 字符集名称
* @return
*/
public final static String MD5(String s, String charsetName)
{
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes(charsetName);
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}