【Python】hmac模块_基于密钥的消息验证

发布时间 2023-05-26 14:34:48作者: Phoenixy

HMAC算法可以用于验证信息的完整性,这些信息可能在应用之间或者网络间传递

 

1、SHA加密

 

# -*- coding:utf-8 -*-

import hmac
import hashlib


class hmac_tools:

    def __init__(self):
        self.key = "a12345678"

    def sha512Encrypt(self, msg):
        h = hmac.new(self.key.encode("utf-8"), msg.encode("utf-8"), "sha512")

        return h.hexdigest()

    def sha384Encrypt(self, msg):
        h = hmac.new(self.key.encode("utf-8"), msg.encode("utf-8"), "sha384")

        return h.hexdigest()

    def sha256Encrypt(self, msg):
        h = hmac.new(self.key.encode("utf-8"), msg.encode("utf-8"), "sha256")

        return h.hexdigest()

    def sha1Encrypt(self, msg):
        h = hmac.new(self.key.encode("utf-8"), msg.encode("utf-8"), hashlib.sha1)
        return h.hexdigest()

    def md5Encrypt(self, msg):
        h = hmac.new(self.key.encode("utf-8"), msg.encode("utf-8"), "md5")
        return h.hexdigest()


if __name__ == "__main__":
    """run"""
    print("sha512加密:", hmac_tools().sha512Encrypt("this is message"))
    print("sha384加密:", hmac_tools().sha384Encrypt("this is message"))
    print("sha256加密:", hmac_tools().sha256Encrypt("this is message"))
    print("sha1加密:", hmac_tools().sha1Encrypt("this is message"))
    print("md5加密:", hmac_tools().md5Encrypt("this is message"))

 

  

执行结果:

 

 

 

 

 

 

官方文档:https://docs.python.org/zh-cn/3/library/hmac.html