利用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)

 

posted @ 2022-04-23 10:25  Jason_huawen  阅读(115)  评论(0编辑  收藏  举报