標籤:imp compute body stringbu err var summary upper build
‘‘‘引入hmac,hashlib加密模組‘‘‘import hmacimport hashlibdef jm_sha256(key, value): ‘‘‘ sha256加密 return:加密結果轉成16進位字串形式,並大寫 ‘‘‘ hsobj = hashlib.sha256(key.encode("utf-8")) hsobj.update(value.encode("utf-8")) return hsobj.hexdigest().upper()def jm_md5(key, value): ‘‘‘ md5加密 return:加密結果轉成16進位字串形式,並大寫 ‘‘‘ hsobj = hashlib.md5(key.encode("utf-8")) hsobj.update(value.encode("utf-8")) return hsobj.hexdigest().upper()def hmac_sha256(key, value): ‘‘‘ hmacsha256加密 return:加密結果轉成16進位字串形式,並大寫 ‘‘‘ message = value.encode(‘utf-8‘) return hmac.new(key.encode(‘utf-8‘), message, digestmod=hashlib.sha256).hexdigest().upper()def hmac_md5(key, value): ‘‘‘ hmacmd5加密 return:加密結果轉成16進位字串形式,並大寫 ‘‘‘ message = value.encode(‘utf-8‘) return hmac.new(key.encode(‘utf-8‘), message, digestmod=hashlib.md5).hexdigest().upper()
其中sha256對應的C#加密方法如下
/// <summary> /// sha256 加密 /// </summary> /// <param name="strkey">加密秘鑰</param> /// <param name="strData">待加密的內容</param> /// <returns></returns> public string GetSHA256HashFromString(string strkey,string strData) { byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(strkey+strData ); try { SHA256 sha256 = new SHA256CryptoServiceProvider(); byte[] retVal = sha256.ComputeHash(bytValue); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("GetSHA256HashFromString() fail,error:" + ex.Message); } } /// <summary> /// hmacsha256 加密 /// </summary> /// <param name="secret">加密秘鑰</param> /// <param name="message">待加密的內容</param> /// <returns></returns> public string CreateToken(string secret,string message) { var encoding = System.Text.Encoding.UTF8; byte[] keyByte = encoding.GetBytes(secret); byte[] messageBytes = encoding.GetBytes(message); using (var hmacsha256 = new HMACSHA256(keyByte)) { byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashmessage.Length; i++) { sb.Append(hashmessage[i].ToString("x2")); } return sb.ToString(); } }
分享python mds,sha256密碼編譯演算法,c#對應sha256密碼編譯演算法