python hashlib库 hmac库加密

hash 256的使用

import hashlib

hash = hashlib.sha256()
hash.update('asd'.encode())
print(hash.hexdigest())

hash = hashlib.sha256()
hash.update('a'.encode())
hash.update('s'.encode())
hash.update('d'.encode())
print(hash.hexdigest())

hash = hashlib.sha256(b'asd').hexdigest()
# hash = hashlib.sha256('asd'.encode()).hexdigest()
print(hash)

hash = hashlib.sha256()
hash.update(b'a')
hash.update(b's')
hash.update(b'd')
print(hash.hexdigest())

hash = hashlib.new('sha256')
# hash.update(b'asd')
hash.update('asd'.encode())
print(hash.hexdigest())

哈希文件校验

import hashlib

while True:
    filepath = input(r'>>>>>输入文件地址(quit退出)>>>>>>:')
    if filepath != 'quit':
        hash = hashlib.sha256()
        try:
            with open(filepath, 'rb') as f:
                for line in f:
                    hash.update(line)
            print(hash.hexdigest())
        except FileNotFoundError:
            print("找不到指定的文件路径,请重新输入")
    else:
        break

一个暴力破解

import hashlib

password = 0

# '10000000'的hash256表示
value = 'fa95b43be4cf8bb030d85e663324ecc5247c2af6272672bfd4bbc1020b40582b'

while password < 100000000:
    hash = hashlib.sha256(str(password).encode())
    if hash.hexdigest() == value:
        print("password = " + str(password))
        break
    else:
        print(str(password) + " is not password")
        password = password + 1

hmac库

import hmac

# 得到相同的hash:
# hamc.new()中的key值需要一样
# # update之后的总内容一样
h1 = hmac.new("tom".encode("utf-8"))
h1.update(b"hello")
h1.update(b"world")
print(h1.hexdigest())

h1 = hmac.new("tom".encode("utf-8"))
h1.update(b"helloworld")
print(h1.hexdigest())

h1 = hmac.new("tomhelloworld".encode("utf-8"))
print(h1.hexdigest())

输出结果

0426ccec3b134e8c18fdcefee841ef25
0426ccec3b134e8c18fdcefee841ef25
ff1214d895bbaf5f1847db4ebae8212e
发布了57 篇原创文章 · 获赞 12 · 访问量 7711

猜你喜欢

转载自blog.csdn.net/volunteer1024/article/details/100179730