所有文件都可以使用Base64进行编码,而Base64是标准字符串,针对这些字符串进行加密,再保存,此时,将无法打开此文件。如果要解密,将加密后的文件,按字符串进行解密,并重新保存为二进制文件。
import base64
# 针对某个文件进行Base64转码并加密保存
def encrypt(filepath):
with open(filepath, mode='rb') as file:
data = file.read()
source = base64.b64encode(data)
# 加密算法:大小写字母右移5位
dest = ''
for c in source:
dest += chr(ord(c)+5)
# 将加密字符串保存到文件中
with open(filepath+'.enc', mode='w') as file:
file.write(dest)
# 删除原始文件
os.remove(filepath)
# 解密
def decrypt(filepath):
with open(filepath, mode='r') as file:
data =file.read()
dest = ''
for c in data:
dest += chr(ord(c)-5)
newfile = filepath.replace('.enc', '')
with open(newfile,mode='wb') as file:
file.write(base64.b64decode(dest))
# 删除加密文件
os.remove(filepath)
if __name__ == '__main__':
encrypt('./test.jpg')
decrypt('./test.jpg.enc')