编程语言
首页 > 编程语言> > 利用Python的Hashlib模块实现各种Hash算法的工具

利用Python的Hashlib模块实现各种Hash算法的工具

作者:互联网

import hashlib
import optparse
import sys

def get_params():
    parser = optparse.OptionParser('Usage: <Program> -m hash_method -c content')
    parser.add_option('-m', '--method', dest='method', type='string', help="Specify Hash Method")
    parser.add_option('-c', '--content', dest='content', type='string', help='Specify the data to hash')
    options, args = parser.parse_args()
    if options.method is None or options.content is None:
        print(parser.usage)
        sys.exit(0)
    return options.content, options.method


def hash_handler(method, content):
    if method == 'md5':
        hashobj = hashlib.md5()
        hashobj.update(content.encode('utf-8'))
        print(hashobj.hexdigest())
    if method == 'sha1':
        hashobj = hashlib.sha1()
        hashobj.update(content.encode('utf-8'))
        print(hashobj.hexdigest())
    if method == 'sha224':
        hashobj = hashlib.sha224()
        hashobj.update(content.encode('utf-8'))
        print(hashobj.digest())
    if method == 'sha256':
        hashobj = hashlib.sha256()
        hashobj.update(content.encode('utf-8'))
        print(hashobj.hexdigest())
    if method == 'sha512':
        hashobj = hashlib.sha512()
        hashobj.update(content.encode('utf-8'))
        print(hashobj.hexdigest())


if __name__ == "__main__":
    
    content_data, method = get_params()
    hash_handler(method, content_data)

 

标签:hashobj,Hashlib,Hash,Python,parser,hashlib,content,print,method
来源: https://www.cnblogs.com/jason-huawen/p/16181614.html