問題重現
這個 API 是當時給 Lyra 應用做激活用的,遂打開 Lyra 試了下,卻發現一切正常,于是可以排除服務端的問題
放出導致錯誤的源碼(來自 MSDN):
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public string CalculateMD5Hash( string input) { // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte [] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte [] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for ( int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString(“X2”)); } return sb.ToString(); } |
實質
MD5 有很多版本,其實這段代碼并沒有錯,但是 php 的 md5 函數默認返回的是 32位小寫 ,而以上這一段返回的是 16位小寫
于是想辦法把這個 func 改為 32位小寫輸出即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public static String md5(String s) { MD5 md5 = new MD5CryptoServiceProvider(); byte [] bytes = System.Text.Encoding.UTF8.GetBytes(s); bytes = md5.ComputeHash(bytes); md5.Clear(); string ret = "" ; for ( int i = 0; i < bytes.Length; i++) { ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0' ); } return ret.PadLeft(32, '0' ); } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
原文鏈接:https://ifengge.me/archives/274.html?utm_source=tuicool&utm_medium=referral