hashlib封装

import hashlib


class HashlibProcess:
    hash_type_dict = {
        "md5": hashlib.md5,
        "SHA1": hashlib.sha1,
        "SHA224": hashlib.sha224,
        "SHA256": hashlib.sha256,
        "SHA384": hashlib.sha384,
        "SHA512": hashlib.sha512,
    }

    def __init__(self, hash_type, salt=""):
        self.hash_type = hash_type
        self.salt = salt
        self.m = HashlibProcess.hash_type_dict.get(self.hash_type, hashlib.md5)(self.salt.encode('utf-8'))

    def set_salt(self, salt):
        self.salt = salt

    def reset_m(self):
        self.m = HashlibProcess.hash_type_dict.get(self.hash_type, hashlib.md5)(self.salt.encode('utf-8'))

    def hashlib_process(self, data):
        """hash类型"""

        self.m.update(data.encode('utf-8'))

    def get_result(self):
        return self.m.hexdigest()


def main():
    good_dict = dict()
    # good_dict = {'md5': {'data': 'good', 'salt': '', 'ret_length': 32, 'ret': '755f85c2723bb39381c7379a604160d8'},
    #              'SHA1': {'data': 'good', 'salt': '', 'ret_length': 40,
    #                       'ret': 'fc19318dd13128ce14344d066510a982269c241b'},
    #              'SHA224': {'data': 'good', 'salt': '', 'ret_length': 56,
    #                         'ret': '29be8090b4c4dbb8bdd4882eb3da04b0b5d6fa092af257d3de5afa69'},
    #              'SHA256': {'data': 'good', 'salt': '', 'ret_length': 64,
    #                         'ret': '770e607624d689265ca6c44884d0807d9b054d23c473c106c72be9de08b7376c'},
    #              'SHA384': {'data': 'good', 'salt': '', 'ret_length': 96,
    #                         'ret': 'c3fdd9a9527ab4346895bc0c78de4a81b56b846479aea64f4b88b1efe745d6cd9b6b13f92603808b6b2e967802c10c4e'},
    #              'SHA512': {'data': 'good', 'salt': '', 'ret_length': 128,
    #                         'ret': '10259bfe1a41058e4671d05a3b962b774c4b16946b4040bc055059d1859d5f15ec4d7f01ca3f7561632d00add6122d337022a151174e5b9cebf430254b8e9fa7'}}

    for hash_type in ["md5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512"]:
        ret = simple_main(hash_type)
        good_dict[hash_type] = dict({"data": "good",
                                     "salt": "",
                                     "ret_length": len(ret),
                                     "ret": ret})

    print(good_dict)


def simple_main(hash_type="md5"):
    # hash_type = "md5"
    salt = ""
    hashlib_process_obj = HashlibProcess(hash_type, salt)
    data = "good"
    hashlib_process_obj.hashlib_process(data)
    ret = hashlib_process_obj.get_result()
    # print(ret)
    return ret


if __name__ == '__main__':
    main()

上一篇:开放数据网站


下一篇:内建模块-hashlib、hmac