我可以使用带有现有openssh密钥对的pyNaCl密封盒吗?

2024-07-04 07:49:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用PyNacl进行不对称加密(公共和私有ssh密钥对)以安全地传输数据

我使用的是以openssh格式使用ssh keygen-t ed25519生成的现有密钥对。(有关我的代码的更多详细信息,请参见下文)

基本上,问题是,以前有人成功地做到了这一点吗?如何做到

在提取了我相当确信的内容之后,这些密钥使用了一个名为openssh密钥解析器的库。(64字节,32个专用,然后32个公用)

"private_public": "b'2\\xfbO\\xab\\xd1\\\\Ie\\xa3\\x8b\\xc9\\x16\\xe8\\xd5\\xfcc\\xdc\\xa5k+H\\tQ\\xae\"\\x1c5+\\x89Q\\xe1p\\xf5\\x01\\xe4\\xfa\\xa1<[5\\xc4\\x07\\xc8\\xf5\\xd5\\xa7\\xbb\\xa3\\xefZm\\x99\\xd7<y\\x96\\xda\\x89x\\x04\\xcc\\x0e8p'"

我使用公钥创建一个密封的盒子来进行加密

#load the public key
server_pubk = (OpenPublicKey.from_string(server_pubk_file_content))
#get exactly the key bytes
server_pubk = server_pubk.params.data['public']
#pass the key bytes to nacl
server_pubk = nacl.public.PublicKey(server_pubk)
#now we create the nacl SealedBox 
sealed_box = SealedBox(server_pubk)
#and encrypt a message
encrypted = sealed_box.encrypt(message)

据我所知,这是意料之中的事。我的问题是,当我试图使用私钥创建一个将解密消息的密封盒时

unseal_box = SealedBox(server_privk)
plaintext = unseal_box.decrypt(encrypted) #does not work with the unhelpful error traceback below :

File "script.py", line 140, in <module>
unseal_box.decrypt(encrypted)
File "/usr/lib/python3.7/site-packages/nacl/public.py", line 361, in decrypt self._private_key,
File "/usr/lib/python3.7/site-packages/nacl/bindings/crypto_box.py", line 318, in crypto_box_seal_open
raising=exc.CryptoError)
File "/usr/lib/python3.7/site-packages/nacl/exceptions.py", line 81, in ensure
raise raising(*args)
nacl.exceptions.CryptoError: An error occurred trying to decrypt the message

我拨弄了一下,注意到当我这样做的时候

server_privk = nacl.public.PrivateKey(server_privk)

要创建将由SealedBox使用的PrivateKey对象,nacl将生成一个公钥(server_privk.public_key属性),该公钥与我知道的第一个SealedBox中使用的正确公钥不匹配

我尝试将server_privk.public_密钥重新分配给我用来制作第一个框的同一个密钥,但这给了我同样的问题

我目前的想法是:

  • 不知何故,我遗漏了openssh格式的工作原理(可能没有获得正确的私钥字节,可能我必须对它们进行转换,可能openssh密钥解析器库把事情搞砸了)
  • 我不应该使用openssh,而是转换我的密钥格式,或者使用另一个库来处理加密

任何答案或想法都将不胜感激:)

参考资料: openssh解析器:https://github.com/scottcwang/openssh_key_parser pyNaCl:https://pynacl.readthedocs.io/en/latest/public/


Tags: thekeypyboxserverline密钥public
1条回答
网友
1楼 · 发布于 2024-07-04 07:49:49

好的,问题解决了,可以将pyNaCl与ed25519一起使用,您只需正确转换密钥。 在这里找到了实现方法:gist.github.com/R-VdP/b7ac0106a4fd395ee1c37bfe6f552a36

有点烦人文档不完整

相关问题 更多 >

    热门问题