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

不知道你是否相信,只需 10 行代码,就可以使用 Python 100% 安全地加密文件。这背后的原理就是 OTP。

10年积累的网站建设、成都做网站经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有奉节免费网站建设让你可以放心的选择与我们合作。

原理

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/Download

分享标题:十行Python代码,使用OTP实现对文件的加密解密
转载来于:http://www.hantingmc.com/qtweb/news45/542245.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联