加解密流程與python3加解密流程一致,參考:https://blog.csdn.net/feitianxuxue/article/details/102961733
區別主要在於:
python2 與python3的編碼問題。
python3中讀取文件只能以二進制方式打開。寫二進制文件時候,以二進制方式寫入。python2 則容易的多。
python3中文本字符和二進制數據分的很清洗,分別用str和bytes表示。python3中base64編碼輸出是bytes,需要轉碼
python3中系統默認使用utf-8編碼。python2中默認使用ASICII編碼。
關於python2和python3的編碼問題,見博客:待寫
python2 加密代碼:
# -*- coding: utf-8 -*-
import os
import base64
from Crypto.Cipher import AES
def ReadTextFile(in_file, mode):
file = open(in_file, mode)
content = file.read()
file.close()
return content
def WriteTextFile(out_file, lines):
file = open(out_file, 'w')
for ln in lines:
file.write(ln+'\n')
file.close()
def AddTo16(s):
return s + (16-len(s)%16) * chr(16-len(s)%16)
def EncryptData(key,text):
#初始化加密器
aes = AES.new(key, AES.MODE_CBC,iv)
# aes = AES.new(base64.b64decode(key), AES.MODE_ECB)
#先進行 aes 加密,返回bytes
encryptAes = aes.encrypt(AddTo16(text))
#用 base64 轉成字符串形式,用於寫入文件
encrypted_text = base64.b64encode(encryptAes)
return encrypted_text
def Encrypt(key):
plaintext = ReadTextFile(in_file,'r')
ciphertext = EncryptData(key, plaintext)
#將密文寫入文件[AES加密使用的鹽|加密後的數據密文]
lines = [base64.b64encode(iv), ciphertext]
WriteTextFile(out_file, lines)
in_file = './data/file.jpg'
out_file = './data/file.jpg.cipher'
iv = os.urandom(16) #AES CBC模式加密使用的salt
#生成256 位密鑰
key = os.urandom(32)
with open("./key","w+") as f:
f.write(key)
#使用密鑰進行加密
Encrypt(key)
python2 解密代碼:
# -*- coding: utf-8 -*-
#!/usr/bin/env python2
import base64
from Crypto.Cipher import AES
def ReadTextFile(in_file):
file = open(in_file, 'r')
lines = []
for ln in file:
lines.append(ln)
file.close()
return lines
def WriteTextFile(out_file, content):
file = open(out_file, 'w')
file.write(content)
file.close()
def aes256unpad(s):
return s[:-ord(s[len(s)-1:])]
def DecryptData(datakey, iv, ciphertext):
#初始化加密器
cryptos = AES.new(datakey, AES.MODE_CBC, iv)
#執行解密運算,並將末尾爲0的字節去掉
plain_text = cryptos.decrypt(ciphertext)
for i in plain_text:
if plain_text[-1] == 0:
plain_text = plain_text[:-1]
else:
break
return aes256unpad(plain_text)
in_file = './data/file.jpg.cipher'
out_file = './data/decrypted_file.jpg'
#讀取本地存儲的加密文件,文件按行寫入格式:[AES加密使用的鹽|加密後的數據密文]
in_lines = ReadTextFile(in_file)
#讀取密鑰
key = open('./key', 'r').read()
#使用明文數據密鑰和鹽解密密文數據
plain_text = DecryptData(key, base64.b64decode(in_lines[0]), base64.b64decode(in_lines[1]))
#將明文數據以二進制形式寫入文件,通過 md5sum 對比原始文件和經過解密後的文件
WriteTextFile(out_file, plain_text)
測試:
對比文件,md5一致