在Python中返回不同结果的MD5哈希
对于类赋值,我应该获取文件的内容,计算MD5散列并将其存储在单独的文件中。然后我应该能够通过比较MD5散列来检查完整性。我对Python和JSON比较陌生,所以我想我应该尝试通过这个任务来解决这些问题,而不是使用我已经知道的东西 无论如何,我的程序从一个文件中读取数据,创建一个散列,然后将该散列存储到一个JSON文件中。问题来自我的诚信检查。当我返回文件的计算哈希结果时,它与JSON文件中记录的结果不同,即使没有对文件进行任何更改。下面是正在发生的事情的一个例子,我也粘贴了我的代码。提前谢谢你的帮助 例如:这些是我的JSON文件的内容 内容:b'我制作了一个文件来测试md5\n' 摘要:1e8f4e6598be2ea2516102de54e7e48e 这是我尝试检查完全相同的文件的完整性时返回的结果(未对其进行任何更改): 内容:b'我制作了一个文件来测试md5\n' 摘要:ef8b7bf2986f59f8a51aae6b496e8954在Python中返回不同结果的MD5哈希,python,json,hash,md5,Python,Json,Hash,Md5,对于类赋值,我应该获取文件的内容,计算MD5散列并将其存储在单独的文件中。然后我应该能够通过比较MD5散列来检查完整性。我对Python和JSON比较陌生,所以我想我应该尝试通过这个任务来解决这些问题,而不是使用我已经知道的东西 无论如何,我的程序从一个文件中读取数据,创建一个散列,然后将该散列存储到一个JSON文件中。问题来自我的诚信检查。当我返回文件的计算哈希结果时,它与JSON文件中记录的结果不同,即使没有对文件进行任何更改。下面是正在发生的事情的一个例子,我也粘贴了我的代码。提前谢谢你的
import hashlib
import json
import os
import fnmatch
from codecs import open
#opens the file, reads/encodes it, and returns the contents (c)
def read_the_file(f_location):
with open(f_location, 'r', encoding="utf-8") as f:
c = f.read()
f.close()
return c
def scan_hash_json(directory_content):
for f in directory_content:
location = argument + "/" + f
content = read_the_file(location)
comp_hash = create_hash(content)
json_obj = {"Directory": argument, "Contents": {"filename": str(f),
"original string": str(content), "md5": str(comp_hash)}}
location = location.replace(argument, "")
location = location.replace(".txt", "")
write_to_json(location, json_obj)
#scans the file, creates the hash, and writes it to a json file
def read_the_json(f):
f_location = "recorded" + "/" + f
read_json = open(f_location, "r")
json_obj = json.load(read_json)
read_json.close()
return json_obj
#check integrity of the file
def check_integrity(d_content):
#d_content = directory content
for f in d_content:
json_obj = read_the_json(f)
text = f.replace(".json", ".txt")
result = find(text, os.getcwd())
content = read_the_file(result)
comp_hash = create_hash(content)
print("content: " + str(content))
print(result)
print(json_obj)
print()
print("Json Obj: " + json_obj['Contents']['md5'])
print("Hash: " + comp_hash)
#find the file being searched for
def find(pattern, path):
result = ""
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result = os.path.join(root, name)
return result
#create a hash for the file contents being passed in
def create_hash(content):
h = hashlib.md5()
key_before = "reallyBad".encode('utf-8')
key_after = "hashKeyAlgorithm".encode('utf-8')
content = content.encode('utf-8')
h.update(key_before)
h.update(content)
h.update(key_after)
return h.hexdigest()
#write the MD5 hash to the json file
def write_to_json(arg, json_obj):
arg = arg.replace(".txt", ".json")
storage_location = "recorded/" + str(arg)
write_file = open(storage_location, "w")
json.dump(json_obj, write_file, indent=4, sort_keys=True)
write_file.close()
#variable to hold status of user (whether they are done or not)
working = 1
#while the user is not done, continue running the program
while working == 1:
print("Please input a command. For help type 'help'. To exit type 'exit'")
#grab input from user, divide it into words, and grab the command/option/argument
request = input()
request = request.split()
if len(request) == 1:
command = request[0]
elif len(request) == 2:
command = request[0]
option = request[1]
elif len(request) == 3:
command = request[0]
option = request[1]
argument = request[2]
else:
print("I'm sorry that is not a valid request.\n")
continue
#if user inputs command 'icheck'...
if command == 'icheck':
if option == '-l':
if argument == "":
print("For option -l, please input a directory name.")
continue
try:
dirContents = os.listdir(argument)
scan_hash_json(dirContents)
except OSError:
print("Directory not found. Make sure the directory name is correct or try a different directory.")
elif option == '-f':
if argument == "":
print("For option -f, please input a file name.")
continue
try:
contents = read_the_file(argument)
computedHash = create_hash(contents)
jsonObj = {"Directory": "Default", "Contents": {
"filename": str(argument), "original string": str(contents), "md5": str(computedHash)}}
write_to_json(argument, jsonObj)
except OSError:
print("File not found. Make sure the file name is correct or try a different file.")
elif option == '-t':
try:
dirContents = os.listdir("recorded")
check_integrity(dirContents)
except OSError:
print("File not found. Make sure the file name is correct or try a different file.")
elif option == '-u':
print("gonna update stuff")
elif option == '-r':
print("gonna remove stuff")
#if user inputs command 'help'...
elif command == 'help':
#display help screen
print("Integrity Checker has a few options you can use. Each option "
"must begin with the command 'icheck'. The options are as follows:")
print("\t-l <directory>: Reads the list of files in the directory and computes the md5 for each one")
print("\t-f <file>: Reads a specific file and computes its md5")
print("\t-t: Tests integrity of the files with recorded md5s")
print("\t-u <file>: Update a file that you have modified after its integrity has been checked")
print("\t-r <file>: Removes a file from the recorded md5s\n")
#if user inputs command 'exit'
elif command == 'exit':
#set working to zero and exit program loop
working = 0
#if anything other than 'icheck', 'help', and 'exit' are input...
else:
#display error message and start over
print("I'm sorry that is not a valid command.\n")
导入hashlib
导入json
导入操作系统
导入fnmatch
从编解码器导入打开
#打开文件,对其进行读取/编码,并返回内容(c)
def read__文件(f_位置):
打开(f_位置,'r',encoding=“utf-8”)作为f:
c=f.read()
f、 关闭()
返回c
def scan_hash_json(目录内容):
对于目录\u内容中的f:
位置=参数+“/”+f
内容=读取文件(位置)
comp_hash=创建_hash(内容)
json_obj={“目录”:参数,“内容”:{“文件名”:str(f),
“原始字符串”:str(内容),“md5”:str(comp_hash)}
位置=位置。替换(参数“”)
位置=位置。替换(“.txt”,”)
将_写入_json(位置,json_obj)
#扫描文件,创建哈希,并将其写入json文件
def读取json(f):
f_location=“录制的”+“/”+f
read_json=open(f_位置,“r”)
json_obj=json.load(读取json)
read_json.close()
返回json_obj
#检查文件的完整性
def检查_完整性(d_内容):
#d_content=目录内容
对于d_内容中的f:
json_obj=读取_json(f)
text=f.replace(“.json”,“.txt”)
结果=查找(文本,os.getcwd())
内容=读取文件(结果)
comp_hash=创建_hash(内容)
打印(“内容:+str(内容))
打印(结果)
打印(json_obj)
打印()
打印(“Json Obj:+Json_Obj['Contents']['md5']))
打印(“散列:+comp_散列)
#查找正在搜索的文件
def查找(模式、路径):
result=“”
对于os.walk(路径)中的根、目录和文件:
对于文件中的名称:
如果fnmatch.fnmatch(名称、模式):
结果=os.path.join(根,名称)
返回结果
#为传入的文件内容创建哈希
def创建_散列(内容):
h=hashlib.md5()
key_before=“reallyBad”。编码('utf-8')
key\u after=“hashKeyAlgorithm.”编码('utf-8')
content=content.encode('utf-8')
h、 更新(之前的键)
h、 更新(内容)
h、 更新(按键后)
返回h.hexdigest()
#将MD5哈希写入json文件
def write_to_json(arg,json_obj):
arg=arg.replace(“.txt”,“.json”)
存储位置=“已记录/”+str(arg)
写入文件=打开(存储位置,“w”)
dump(json_obj,write_文件,缩进=4,排序键=True)
write_file.close()
#保存用户状态的变量(无论是否完成)
工作=1
#用户未完成时,继续运行程序
工作时==1:
打印(“请输入命令。对于帮助,请键入“帮助”。对于退出,请键入“退出”)
#获取用户的输入,将其划分为单词,然后获取命令/选项/参数
请求=输入()
request=request.split()
如果len(请求)==1:
命令=请求[0]
elif len(请求)=2:
命令=请求[0]
选项=请求[1]
elif len(请求)=3:
命令=请求[0]
选项=请求[1]
参数=请求[2]
其他:
打印(“很抱歉,这不是一个有效的请求。\n”)
持续
#如果用户输入命令“icheck”。。。
如果命令=='icheck':
如果选项=='-l':
如果参数==“”:
打印(“对于选项-l,请输入目录名。”)
持续
尝试:
dirContents=os.listdir(参数)
扫描\u哈希\u json(目录内容)
除操作错误外:
打印(“未找到目录。请确保目录名称正确,或尝试其他目录。”)
elif选项=='-f':
如果参数==“”:
打印(“对于选项-f,请输入文件名。”)
持续
尝试:
contents=读取文件(参数)
computedHash=创建\u散列(内容)
jsonObj={“目录”:“默认”,“内容”:{
“文件名”:str(参数),“原始字符串”:str(内容),“md5”:str(计算哈希)}
将_写入_-json(参数,jsonObj)
除操作错误外:
打印(“未找到文件。请确保文件名正确或尝试其他文件。”)
elif选项=='-t':
尝试:
dirContents=os.listdir(“已录制”)
检查_完整性(目录)
除操作错误外:
打印(“未找到文件。请确保文件名正确或尝试其他文件。”)
elif选项=='-u':
打印(“要更新内容”)
elif选项=='-r':
打印(“要删除内容”)
#如果用户输入命令“帮助”。。。
elif命令==“帮助”:
#显示帮助屏幕
打印完整性检查器有几个
#create a hash for the file contents being passed in
def create_hash(content):
key_before = "reallyBad".encode('utf-8')
key_after = "hashKeyAlgorithm".encode('utf-8')
print("Content: " + str(content))
h.update(key_before)
h.update(content)
h.update(key_after)
print("digest: " + str(h.hexdigest()))
return h.hexdigest()
Please input a command. For help type 'help'. To exit type 'exit'
icheck -f ok.txt Content: this is a test
digest: 1f0d0fd698dfce7ce140df0b41ec3729 Please input a command. For
help type 'help'. To exit type 'exit' icheck -t Content: this is a
test
digest: 1f0d0fd698dfce7ce140df0b41ec3729 Please input a command. For
help type 'help'. To exit type 'exit'
def scan_hash_json(directory_content):
...
location = location.replace(".txt", "")
write_to_json(location, json_obj)
def write_to_json(arg, json_obj):
arg = arg.replace(".txt", ".json")