AES加密文件后附加到图片后面传输
加密过程为:1、将文档压缩成zip;2、将zip字节流用aes加密;3、将加密后的字节流附加到图片后面。
解密流程为:1、从图片后面取出加密后的字节流;2、使用aes解密出zip数据;3、解压zip。
import zipfile
from pathlib import Path
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
# The following variables modified or not is optional.
aes_key = 'justwrapaplaintobase64'
separator = b'donotdonotdonotdothis'
hiden_data_zip_filename = 'h.zip' # 目标文件压缩后的zip
hiden_data_extract_zip_filename = 'eh.zip' # 从img提取出的zip
# Someone who using this program should moidfy the following variables.
hiden_filename = 'ok.xlsx' # 目标文件
original_img_filename = 'aa.png' # 原img
encrypted_img_filename = 'wx.png' # 拼合后的img
def append_data_to_image(image_path: str, append_data: bytes):
image_data = Path(image_path).read_bytes()
with Path(encrypted_img_filename).open('wb') as new_img_file:
new_img_file.write(image_data)
new_img_file.write(separator)
new_img_file.write(append_data)
def extract_data_from_image(image_path: str):
img_data = Path(image_path).read_bytes()
if img_data.find(separator) == -1:
raise Exception("Target data not found.")
return img_data[img_data.find(separator) + len(separator):]
def zip_file(file_path: str, zip_path: str) -> bytes:
with zipfile.ZipFile(zip_path, 'w') as zipf:
zipf.write(file_path)
return Path(zip_path).read_bytes()
def unzip_file():
with zipfile.ZipFile(hiden_data_zip_filename, 'r') as zip_ref:
zip_ref.extractall(str(Path(__file__).parent))
def aes_encrypt(data_bytes: bytes, key: bytes) -> bytes:
cipher = AES.new(key, AES.MODE_CBC)
iv = cipher.iv
padded_data = pad(data_bytes, AES.block_size)
ciphertext = cipher.encrypt(padded_data)
return iv + ciphertext
def aes_decrypt(encrypted_data: bytes, key: bytes) -> bytes:
iv = encrypted_data[:AES.block_size]
ciphertext = encrypted_data[AES.block_size:]
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_plaintext = cipher.decrypt(ciphertext)
plaintext = unpad(padded_plaintext, AES.block_size)
return plaintext
def init_aes_key(key: str) -> bytes:
if len(key) == 0:
raise Exception("At least one char of key was needed.")
return ((key * 16)[:16]).encode('utf8')
def append_data_demo():
zip_data = zip_file(hiden_filename, hiden_data_zip_filename)
encrypted_zip_data = aes_encrypt(zip_data, init_aes_key(aes_key))
append_data_to_image(original_img_filename, encrypted_zip_data)
def extract_data_demo():
extract_data = extract_data_from_image(encrypted_img_filename)
original_data = aes_decrypt(extract_data, init_aes_key(aes_key))
Path(hiden_data_extract_zip_filename).write_bytes(original_data)
unzip_file()
if __name__ == "__main__":
append_data_demo()
extract_data_demo()
有了计划记得推动,不要原地踏步。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2020-12-11 linux 系统安装 pip