10 行 Python 代码,使用 OTP 实现对文件的加密解密
2023-02-19 12:20:47 时间
不知道你是否相信,只需 10 行代码,就可以使用 Python 100% 安全地加密文件。这背后的原理就是 OTP。
原理
OTP 就是 One-time password,翻译过来就是一次性密码。它的原理非常简单,加密的过程就是明文和密钥(key)进行异或,得到密文,而解密的过程就是密文和密钥(key)异或,得到明文。举例如下:
加密(此处图贴错了,应该是二进制,抱歉):
解密:
理论上,基于以下假设,这个加密被认为是牢不可破的:
- 密钥是真正随机的
- 密钥长度与信息长度相同
- 密钥永远不会全部或部分重复使用
- 密钥 key 很安全,不会公开
应用:加密文件
如果自己有一个私密的文件,那么完全可以使用 OTP 来加密,密钥保存在自己手里,很安全。话不多说,直接上代码:
加密文件:
import os
def encryption(file):
toBeEncryptedFile = open(file, 'rb').read()
size = len(toBeEncryptedFile)
otpKey = os.urandom(size)
with open(file.split('.')[0] + '.key', 'wb') as key:
key.write(otpKey)
encryptedFile = bytes (a ^ b for (a, b) in zip(toBeEncryptedFile, otpKey))
with open(file, 'wb') as encrypted:
encrypted.write(encryptedFile)
这段代码一共 10 行,密钥 optKey 随机生成并保存在文件中,然后用这个密钥加密文件,当需要加密文件时,这样调用 encryption 函数:
if __name__ == "__main__":
encryption("/Users/aaron/Downloads/1/银行卡.JPG")
成功执行代码后,我们无法再预览或打开我们的图像,因为它现在是加密的。此外,我们的文件夹中有一个新的密钥文件“银行卡.key”。
现在,我们来解密它。
解密文件只需要 6 行代码:
def decryption(file, otpKey):
encryptedFile = open(file, 'rb').read()
otpKey = open(otpKey, 'rb').read()
decryptedFile = bytes (a ^ b for (a, b) in zip(encryptedFile, otpKey))
with open(file, 'wb') as decrypted:
decrypted.write(decryptedFile)
这样调用:
if __name__ == "__main__":
# encryption("/Users/aaron/Downloads/1/银行卡.JPG")
decryption("/Users/aaron/Downloads/1/银行卡.JPG", "/Users/aaron/Downloads/1/银行卡.key")
这样就完成了解密:
完整代码
import os
def encryption(file):
toBeEncryptedFile = open(file, "rb").read()
size = len(toBeEncryptedFile)
otpKey = os.urandom(size)
with open(file.split(".")[0] + ".key", "wb") as key:
key.write(otpKey)
encryptedFile = bytes(a ^ b for (a, b) in zip(toBeEncryptedFile, otpKey))
with open(file, "wb") as encrypted:
encrypted.write(encryptedFile)
def decryption(file, otpKey):
encryptedFile = open(file, "rb").read()
otpKey = open(otpKey, "rb").read()
decryptedFile = bytes(a ^ b for (a, b) in zip(encryptedFile, otpKey))
with open(file, "wb") as decrypted:
decrypted.write(decryptedFile)
if __name__ == "__main__":
# encryption("/Users/aaron/Downloads/1/银行卡.JPG")
decryption("/Users/aaron/Downloads/1/银行卡.JPG", "/Users/aaron/Downloads/1/银行卡.key")
最后
本文分享了 One-Time Pad 加密概念背后的理论,并用它实现了文件的加密和解密
相关文章
- 用 Python 写个贪吃蛇,保姆级教程!
- 让你的程序炫起来!少有人知道但超酷的 Python 进度条开源库
- Python Serverless 开源框架:Zappa(详细教程)
- 初窥 Python 的 import 机制
- 如何建立一个完美的 Python 项目
- pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available
- Python 图像边缘检测 | 利用 opencv 和 skimage 的 Canny 算法
- Python进阶之递归算法详解
- Python AI小项目打包通关:Pyinstaller和Wix都用上了
- Generator(生成器),入门初基,Coroutine(原生协程),登峰造极,Python3.10并发异步编程async底层实现
- CentOS7 Python 3.7.0 编译安装
- Python 运算符与数据类型
- Python 流程控制与循环体
- Python 变量作用域与函数
- Python 装饰&生成&迭代器
- Python 常用内置模块详解
- Python 正则表达模块详解
- Python 异常处理与反射机制
- Python 线程&进程与协程
- Python Socket套接字编程