java和c# md5加密

MD5加密的方式有很多,加盐的方式更多,最近项目需要java和c#加密结果一致,形成方法如下:

1.c#加密方法
/// <summary>
/// MD5 加密字符串
/// </summary>
/// <param name="rawPass">源字符串</param>
/// <returns>加密后字符串</returns>
public static string MD5Encoding(string rawPass)
{
// 创建MD5类的默认实例:MD5CryptoServiceProvider
MD5 md5 = MD5.Create();
byte[] bs = Encoding.UTF8.GetBytes(rawPass);
byte[] hs = md5.ComputeHash(bs);
StringBuilder sb = new StringBuilder();
foreach (byte b in hs)
{
// 以十六进制格式格式化
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2.java加密方法
/**
* @param text
* @return 传统的MD5加密方式,与客户端加密方法相同
* @throws Exception
*/
public static String TraditionMd5(String text) throws Exception {
//加密后的字符串
byte[] bytes=text.getBytes("utf-8");
byte[] encodeStrByte=DigestUtils.md5Digest(bytes);
String re=bytesToHexFun1(encodeStrByte);
return re;
}

private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

/**
* byte[]数组转16进制字符串
* @param bytes
* @return
*/
public static String bytesToHexFun1(byte[] bytes) {
// 一个byte为8位,可用两个十六进制位标识
char[] buf = new char[bytes.length * 2];
int a = 0;
int index = 0;
for(byte b : bytes) { // 使用除与取余进行转换
if(b < 0) {
a = 256 + b;
} else {
a = b;
}

buf[index++] = HEX_CHAR[a / 16];
buf[index++] = HEX_CHAR[a % 16];
}

return new String(buf);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
里面带了 byte[] 转了十六进制的bytesToHexFun1方法

ps :双倍加盐加密
public static String DoubleSlatTraditionMd5(String str) throws Exception {
String tmp=TraditionMd5(str+ "{" +salt + "}");
tmp=TraditionMd5(tmp+ "{" +salt + "}");
return tmp;
}
1
2
3
4
5
参考资料
https://blog.csdn.net/worm0527/article/details/69939307
---------------------
作者:黑鸦log
来源:CSDN
原文:https://blog.csdn.net/c0411034/article/details/82256597
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/Alex80/p/10911213.html
今日推荐