分享python mds,sha256加密算法,c#对应sha256加密算法

学习编程 2018-01-12

'''
引入hmac,hashlib加密模块
'''
import hmac
import hashlib


def 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();
            }
        }

相关推荐