js和python中使用CryptoJS.SHA256做加密算法详解

加密方式是:先使用sha256进行加密,然后用base64转码,计算当前GMT时间,使用hmacsha256加密,最后得到base64码,即为签名。
js中使用:

<script src="crypto-js.min.js"></script>
function get_sha256(str, secret) {
    // 计算sha256
    var sha256 = CryptoJS.SHA256(str)
    sha256 = CryptoJS.enc.Base64.stringify(sha256);
    var digest = "SHA-256=" + sha256;
    // 获取格式GMT格式时间
    var gmt_date = new Date().toGMTString();
    var qq = "x-date: " + gmt_date + "\ndigest: " + digest;
    // hmac_sha256加密
    var signature = CryptoJS.HmacSHA256(qq, secret);
    signature = CryptoJS.enc.Base64.stringify(signature);
    console.log(signature);
    return signature
}

get_sha256("abcd", "your secret")

python3.6中使用:

import datetime
import hashlib
import base64
import hmac


# 获取格式GMT格式时间
def get_gmt_timestr():
gmt_formate = '%a, %d %b %Y %H:%M:%S GMT'
t = datetime.datetime.utcnow().strftime(gmt_formate)
return t

# hmac_sha256加密
def get_hmac_sha256(message, secret):
message = message.encode('utf-8')
secret = secret.encode('utf-8')
signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest()).decode("utf-8")
return signature

# 计算sha256
def get_sha256(message):
sha256 = hashlib.sha256()
sha256.update(message.encode('utf-8'))
res = base64.b64encode(bytes.fromhex(sha256.hexdigest())).decode("utf-8")
return res

def echo(data, secret):
digest = "SHA-256=%s" % get_sha256(data)
gmt_date = get_gmt_timestr()
signature = get_hmac_sha256("x-date: %s\ndigest: %s" % (gmt_date, digest), secret)
print(signature)


if __name__ == "__main__":
echo("abcd", "your secret")

参考网址:
https://stackoverflow.com/questions/29432506/how-to-get-digest-representation-of-cryptojs-hmacsha256-in-js
https://www.cnblogs.com/devcjq/articles/5971564.html
https://www.cnblogs.com/japhasiac/p/7739846.html
https://www.cnblogs.com/jackiehe/p/4648963.html
https://blog.csdn.net/zwc2xm/article/details/79301237http://www.thinkasp.cn/show/51.html#acr-12
https://segmentfault.com/q/1010000012305581
http://www.sharejs.com/codes/javascript/7311
膜拜大佬~~

猜你喜欢

转载自blog.csdn.net/qq_35790269/article/details/82012963