Java C# 通用MD5加密
C#:
/// <summary>
/// MD5加密
/// </summary>
/// <param name="plaintext">明文</param>
/// <param name="salt">盐</param>
/// <returns>密文(16进制)</returns>
public static string EncryptMd5Hex(string plaintext)
{
MD5 md5 = MD5.Create();
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] ciphertextBytes = md5.ComputeHash(plaintextBytes);
return BytesToHexStr(ciphertextBytes);
}
/// <summary>
/// 字节数组 -> 十六进制字符串
/// </summary>
/// <param name="Bytes"></param>
/// <returns>十六进制字符串</returns>
public static string BytesToHexStr(byte[] Bytes)
{
// 准备十六进制字符串
string result = "";
// 检查字节数组是否为空
if (Bytes == null)
return null;
// 遍历字节数组
for (int i = 0; i < Bytes.Length; i++)
result += Bytes[i].ToString("X2");
// 返回结果
return result;
}
/// <summary>
/// 十六进制字符串 -> 字节数组
/// </summary>
/// <param name="HexString">十六进制字符串</param>
/// <returns>字节数组</returns>
public static byte[] HexStrToBytes(string HexString)
{
// 检查十六进制字符串是否为奇数
if (HexString.Length % 2 == 1)
{
return null;
}
// 十六进制字符串去重空白符
HexString = Regex.Replace(HexString, @"\s", "");
// 准备字节数组
byte[] result = new byte[HexString.Length / 2];
// 遍历十六进制字符串
for (int i = 0; i < result.Length; i++)
result[i] = Convert.ToByte(HexString.Substring(i * 2, 2), 16);
// 返回结果
return result;
}
Java:
/**
* MD5加密
*
* @param plaintext 明文
* @return 密文(16进制)
*/
public static String EncryptMd5Hex(String plaintext) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] plaintextBytes = (plaintext).getBytes("utf-8");
byte[] ciphertextBytes = md.digest(plaintextBytes);
return bytes2HexStr(ciphertextBytes);
} catch (NoSuchAlgorithmException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
/**
* 字节 --> 十六进制字符串
*
* @param bytes 字节
* @return 十六进制字符串
*/
public static String bytes2HexStr(byte[] bytes) {
// 检查字节是否为空
if (bytes.length < 1)
return null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 十六进制字符串 --> 字节
*
* @param hexStr 十六进制字符串
* @return 字节
*/
public static byte[] hexStr2Bytes(String hexStr) {
// 检查十六进制字符串是否为空
if (hexStr == null || "".equals(hexStr.trim()))
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}