libnacl 的 API 的设计方式是,想要安全通信的两方必须以某种方式交换他们的公钥。假设 Alice 想向 Bob 发送一条消息。
# Alice's computer: Bob's computer:
alice_sign = libnacl.public.SecretKey() bob_enc = libnacl.public.SecretKey()
alice_spk_h = alice_sign.hex_pk() bob_epk_h = bob_enc.hex_pk()
# magic happens where alice_spk_h goes to Bob and bob_epk_h goes to alice (i.e. by phone)
bob_epk = libnacl.public.PublicKey(bob_epk_h) alice_spk = libnacl.public.PublicKey(
alice_spk_h)
alice_box = libnacl.public.Box( bob_box = libnacl.public.Box(
alice_sign.sk, bob_epk) bob_enc.sk, alice_spk)
# preparation is done, let's start encrypting...
ct = alice_box.encrypt(msg)
# send ct to Bob (the message is protected)
msg = bob_box.decrypt(ct)
如您所见,您需要分别处理公钥和私钥,以便在通信双方的机器之间发送它们。您不能将它们组合成一种方法,因为这会与 libnacl 的公钥加密的使用场景相矛盾。
请记住,每方使用一个密钥对,只允许向一个方向发送加密消息。如果您需要发回消息,则每一方都需要有两个密钥(一个用于签名,一个用于加密;请注意,我以某种方式命名了 Alice 和 Bob 的密钥以明确这一点)。
有没有办法在一个文件中生成密钥并将密钥存储到一个盒子中+加密/解密到另一个文件中?
是的,但是在这里您必须考虑这些文件在做什么。Python 文件就是代码。如果您从命令行运行生成 SecretKey 的代码,则需要以某种方式存储它,因为再次运行代码会更改密钥。
基因.py
import libnacl.public
def genkey():
return libnacl.public.SecretKey()
def gen_keys_and_save():
# Generate two key pairs and store them for later use
enc = genkey()
enc.save('myencsecret.key')
with open('myencpublic.key', 'w') as pkf:
pkf.write(enc.hex_pk())
sign = genkey()
sign.save('mysignsecret.key')
with open('mysignpublic.key', 'w') as pkf:
pkf.write(sign.hex_pk())
if __name__ == "__main__":
# this code only runs when executed directly (i.e. from command line)
gen_keys_and_save()
压缩包
import libnacl.public
import libnacl.utils
def encrypt(mysignsecret, theirencpublic, data):
box = libnacl.public.Box(mysignsecret, theirencpublic)
return box.encrypt(data)
def parse_and_encrypt(mysignsecretfile, theirencpublicfile, data):
sk = libnacl.utils.load_key(mysignsecretfile)
with open(theirencpublicfile, 'r') as pkf:
pk = libnacl.public.PublicKey(pkf.read())
return encrypt(sk, pk, data)
if __name__ == "__main__":
parse_and_encrypt('mysignsecret.key', 'theirencpublic.key', 'some kind of msg')
解码器
import libnacl.public
def decrypt(myencsecret, theirsignpublic, ciphertext):
box = libnacl.public.Box(myencsecret, theirsignpublic)
return box.decrypt(ciphertext)
# similar to enc.py ...
现在你可以像这样运行它:
$ python gen.py
现在您需要接收他们的encpublic.key 并发送mysignpublic.key。完成后,您可以这样做:
$蟒蛇编码.py