因为毕设要用到文件加密,所以写了先写了个文件加密的demo来学习一下
哈希 MD5
用到了hashlib模块中的md5
from hashlib import md5
def md5_file(name):
m = md5()
a_file = open(name, 'rb') #需要使用二进制格式读取文件内容
m.update(a_file.read())
a_file.close()
return m.hexdigest()
if __name__ == '__main__':
key = md5_file('temp/flask1.py')
AES 加密、解密
因为是文件加密,所以采用的对称加密的形式,不需要对文件进行前面验证
采用了pycryto模块的 AES
from hashlib import md5
import base64
from Crypto.Cipher import AES
def md5_file(name):
m = md5()
a_file = open(name, 'rb') #需要使用二进制格式读取文件内容
m.update(a_file.read())
a_file.close()
return m.hexdigest()
'''
采用AES对称加密算法
'''
# str不是32的倍数那就补足为16的倍数
def add_to_32(value):
while len(value) % 32 != 0:
value += '\0'
return str.encode(value) # 返回bytes
#加密方法
def encrypt_oracle(key,source_filepath,dst_filepath):
raw_file = open(source_filepath,'r')
encry_file = open(dst_filepath,'w')
aes = AES.new(add_to_32(key), AES.MODE_ECB)
encrypt_aes = aes.encrypt(add_to_32(raw_file.read()))
encry_file.write(str(base64.encodebytes(encrypt_aes),encoding='utf-8'))
encry_file.close()
raw_file.close()
return 'ok'
#解密方法
def decrypt_oralce(key,source_filepath,dst_filepath):
raw_file = open(source_filepath,'r')
decry_file = open(dst_filepath,'w')
aes = AES.new(add_to_32(key), AES.MODE_ECB)
base64_decrypted = base64.decodebytes(raw_file.read().encode(encoding='utf-8'))
decry_file.write(str(aes.decrypt(base64_decrypted),encoding='utf-8').replace('\0',''))
decry_file.close()
raw_file.close()
return 'ok'
if __name__ == '__main__':
key = md5_file('temp/flask1.py')
encrypt_oracle(key,'temp/flask1.py','temp/flask11.py')
decrypt_oralce(key,'temp/flask11.py','temp/flask12.py')
参考: