文章目录
- 1. hashlib库
- 1.1 hash对象
- 1.2 hash对象的方法
- 2. 使用sha256生成哈希值
- 2.1 生成字符串的哈希值
- 2.2 生成文件的哈希值
- 3. 使用md5生成哈希值
- 3.1 生成字符串的哈希值
- 3.2 生成文件的哈希值
1. hashlib库
利用python的hashlib
库,可以实现使用sha256
、md5
等加密算法生成哈希值。
1.1 hash对象
hash对象 | 描述 |
---|---|
md5() | md5算法加密 |
sha1() | sha1算法加密 |
sha224() | sha224算法加密 |
sha256() | sha256算法加密 |
sha384() | sha384算法加密 |
sha512() | sha512算法加密 |
1.2 hash对象的方法
方法 | 描述 |
---|---|
copy() | 复制一个hash对象 |
digest() | 返回bytes类型的hash值 |
hexdigest() | 返回str类型的hash值 |
update() | 传入编码后的字符串 |
2. 使用sha256生成哈希值
2.1 生成字符串的哈希值
from hashlib import sha256
def generate_sha256_hashCode(plainText):
plainTextBytes = plainText.encode('utf-8') # 字符串在哈希之前,需要编码
encryptor = sha256()
encryptor.update(plainTextBytes)
hashCode = encryptor.hexdigest()
print(hashCode)
if __name__ == "__main__":
generate_sha256_hashCode('123')
运行结果:
a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3
2.2 生成文件的哈希值
from hashlib import sha256
def generate_sha256_hashCode(filePath):
with open(filePath, encoding="utf-8") as f:
plainText = f.read()
plainTextBytes = plainText.encode('utf-8')
encryptor = sha256()
encryptor.update(plainTextBytes)
hashCode = encryptor.hexdigest()
print(hashCode)
if __name__ == "__main__":
generate_sha256_hashCode('')
3. 使用md5生成哈希值
使用md5
或其他算法,同sha256
,只需要改动以下两行即可:
from hashlib import 算法名
encryptor = 算法名()
3.1 生成字符串的哈希值
from hashlib import md5
def generate_md5_hashCode(plainText):
plainTextBytes = plainText.encode('utf-8')
encryptor = md5()
encryptor.update(plainTextBytes)
hashCode = encryptor.hexdigest()
print(hashCode)
if __name__ == "__main__":
generate_md5_hashCode('123')
运行结果:
202cb962ac59075b964b07152d234b70
3.2 生成文件的哈希值
from hashlib import md5
def generate_md5_hashCode(filePath):
with open(filePath, encoding="utf-8") as f:
plainText = f.read()
plainTextBytes = plainText.encode('utf-8')
encryptor = md5()
encryptor.update(plainTextBytes)
hashCode = encryptor.hexdigest()
print(hashCode)
if __name__ == "__main__":
generate_md5_hashCode('')