十行 Python 代码,使用 OTP 实现对文件的加密解密

时间:2025-11-27 02:58:18来源:运维技术实践作者:人工智能

不知道你是代对文否相信,只需 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)1.2.3.4.5.6.7.8.9.10.

这段代码一共 10 行 ,密钥 optKey 随机生成并保存在文件中,然后用这个密钥加密文件,当需要加密文件时  ,这样调用 encryption 函数:

复制if __name__ == "__main__": encryption("/Users/aaron/Downloads/1/银行卡.JPG")1.2.

成功执行代码后 ,我们无法再预览或打开我们的图像 ,高防服务器因为它现在是加密的 。此外 ,我们的文件夹中有一个新的密钥文件“银行卡.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)1.2.3.4.5.6.

这样调用:

复制if __name__ == "__main__": # encryption("/Users/aaron/Downloads/1/银行卡.JPG") decryption("/Users/aaron/Downloads/1/银行卡.JPG", "/Users/aaron/Downloads/1/银行卡.key")1.2.3.

这样就完成了解密:

完整代码

复制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/Download1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.
相关内容
推荐内容