Created
August 4, 2020 09:54
-
-
Save zeruns/015317b1ddac1957b8d5ee3afad4ba90 to your computer and use it in GitHub Desktop.
Python calculates the MD5/SHA value of a string or file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python计算字符串或文件的MD5/SHA值 | |
import time | |
import os | |
import hashlib | |
# 计算文件的MD5/SHA值 | |
def file(path, algorithm): | |
global start, end # 声明全局变量 | |
start = time.time() # 获取当前时间,用于记录计算过程的耗时 | |
size = os.path.getsize(path) # 获取文件大小,单位是字节(byte) | |
with open(path, 'rb') as f: # 以二进制模式读取文件 | |
while size >= 1024 * 1024: # 当文件大于1MB时将文件分块读取 | |
algorithm.update(f.read(1024 * 1024)) | |
size -= 1024 * 1024 | |
algorithm.update(f.read()) | |
end = time.time() # 获取计算结束后的时间 | |
print() | |
print(algorithm.hexdigest()) # 输出计算结果 | |
# 计算字符串的MD5/SHA值 | |
def str(text, algorithm): | |
global start, end | |
start = time.time() | |
algorithm.update(text.encode(encoding='UTF-8')) | |
end = time.time() | |
print() | |
print(algorithm.hexdigest()) | |
print('https://blog.zeruns.tech') | |
print('1.MD5 2.SHA1 3.SHA224 4.SHA256 5.SHA384 6.SHA512') | |
flag1 = int(input('请选择算法:')) | |
print('\n1.文件 2.字符串') | |
flag2 = int(input('请选择要计算的是文件还是字符串:')) | |
if flag2 == 1: | |
path = input('\n请输入要计算的文件的目录(若跟脚本同目录直接输入文件名即可):') | |
if flag1 == 1: | |
file(path, hashlib.md5()) | |
elif flag1 == 2: | |
file(path, hashlib.sha1()) | |
elif flag1 == 3: | |
file(path, hashlib.sha224()) | |
elif flag1 == 4: | |
file(path, hashlib.sha256()) | |
elif flag1 == 5: | |
file(path, hashlib.sha384()) | |
elif flag1 == 6: | |
file(path, hashlib.sha512()) | |
elif flag2 == 2: | |
text = input('\n请输入要加密的字符串:') | |
if flag1 == 1: | |
str(text, hashlib.md5()) | |
elif flag1 == 2: | |
str(text, hashlib.sha1()) | |
elif flag1 == 3: | |
str(text, hashlib.sha224()) | |
elif flag1 == 4: | |
str(text, hashlib.sha256()) | |
elif flag1 == 5: | |
str(text, hashlib.sha384()) | |
elif flag1 == 6: | |
str(text, hashlib.sha512()) | |
print("\n计算耗时: %s seconds" % (end - start)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment