python - 使用pynacl用一个文件加密,用第二个文件解密
问题描述
我有一些我在下面用 Python 2.7 编写的代码,并使用了 pynacl,在 mac os x 上运行。它目前的工作方式如下所示,它将加密密码,然后再解密。我想知道解密的最后几行是否可以在单独的python文件上?单独的 python 文件是一个每天运行的 cronjob,需要密码才能运行,这就是为什么我需要将解密部分放在文件 #2 上的原因。请让我知道任何建议。
我尝试将文件#1 导入到文件#2,甚至将文件#1 中所需的变量保存到文件中,但是“SealedBox”无法保存到错误“TypeError:参数1 必须可转换为缓冲区的文件中,不是密封盒”
#!/usr/bin/env python2
import nacl.utils
from nacl.public import PrivateKey, SealedBox
import getpass
# Generate Bob's private key, as we've done in the Box example
skbob = PrivateKey.generate()
pkbob = skbob.public_key
# Alice wishes to send a encrypted message to Bob,
# but prefers the message to be untraceable
sealed_box = SealedBox(pkbob)
# This is Alice's message
message = getpass.getpass("LDAP Password is:")
# Encrypt the message, it will carry the ephemeral key public part
# to let Bob decrypt it
encrypted = sealed_box.encrypt(message)
# Store the data with binary mode:
# with open('file.bin', 'wb') as f:
# f.write(encrypted)
unseal_box = SealedBox(skbob)
# with open('file2.bin', 'wb') as f:
# f.write(unseal_box)
# decrypt the received message, this is where File #2 would start
plaintext = unseal_box.decrypt(encrypted)
print(plaintext.decode('utf-8'))
解决方案
你可以使用泡菜:
加密脚本
from nacl.public import PrivateKey, SealedBox
import getpass
import pickle
# Generate Bob's private key, as we've done in the Box example
skbob = PrivateKey.generate()
pkbob = skbob.public_key
# Alice wishes to send a encrypted message to Bob,
# but prefers the message to be untraceable
sealed_box = SealedBox(pkbob)
# This is Alice's message
message = getpass.getpass("LDAP Password is:")
# Encrypt the message, it will carry the ephemeral key public part
# to let Bob decrypt it
encrypted = sealed_box.encrypt(message.encode())
# Store the data with binary mode:
with open('file.bin', 'wb') as f:
pickle.dump(encrypted, f)
with open('file2.bin', 'wb') as f:
pickle.dump(skbob, f)
解密脚本
from nacl.public import SealedBox
import pickle
with open('file.bin', 'rb') as f:
encrypted = pickle.load(f)
with open('file2.bin', 'rb') as f:
skbob = pickle.load(f)
unseal_box = SealedBox(skbob)
# decrypt the received message, this is where File #2 would start
plaintext = unseal_box.decrypt(encrypted)
print(plaintext.decode('utf-8'))
推荐阅读
- python - 不支持的 ONNX opset 版本:11
- javascript - 我如何在视图渲染之前获取 ajax 并分配数据
- asp.net - 单击按钮时防止页面重新加载
- excel - 如何在特定行(VBA)上方添加新行?
- twitter-bootstrap - 如果移动,Bootstrap 4 移动到新行
- setcookie - IBM Http Server - 无法更新 cookie
- django - 模板中未显示的表单中的 DJANGO 初始值(有些不显示)
- laravel - 在 https 中加载 swagger UI 内容 - Lumen
- ms-access-2010 - 我可以在 Ms Access Form 的未绑定文本字段中的 Dcount 公式后添加文本吗?
- vue.js - Promise 被拒绝并且无法在 VUE 和 Directus 中获取Collections 或 getItems