python - 使用 pynacl 使用一个文件加密并使用第二个文件解密

标签 python encryption public-key-encryption pynacl

我有一些代码是用 Python 2.7 编写的,并使用 pynacl,在 mac os x 上运行。目前它的工作方式如下所示,它将加密密码,然后稍后解密。我想知道解密的最后几行是否可以位于单独的 python 文件中?单独的 python 文件是一个每天运行的 cronjob,需要密码才能运行,这就是为什么我需要将解密部分放在文件 #2 上的原因。有任何建议请告诉我。

我尝试将文件 #1 导入到文件 #2,甚至将文件 #1 中所需的变量保存到文件中,但“SealedBox”无法保存到文件中,并出现错误“TypeError:参数 1 必须可转换为缓冲区,而不是 SealedBox”

#!/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 - 使用 pynacl 使用一个文件加密并使用第二个文件解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085720/

相关文章:

python - 在 django 中使用缓存 - 如何创建 key

python - 非 root 执行命令

c# - Universal Windows Platform (UWP) 中的加密/解密有数据错误(循环冗余校验)

c - C 示例中的 AES、Serpent 或 Twofish?

java - 如何配置 SonarCloud

amazon-web-services - AWS CentOS 根 key 对

encryption - 我可以使用带有两个私钥的非对称加密吗?

java - 在没有库的情况下读取 Java 中的 PKCS#1 或 SPKI 公钥

python - 绘制分组的 Pandas 数据框

python - 哪个更 Pythonic 调用 __str__() 方法或转换为 str()?