使用没有 ssh-keygen -p 的 python 库解密 Ed25519 私钥

问题描述

我有私钥,例如生成 RSA 密钥对:

ssh-keygen -t rsa -N 123456 -f /tmp/rsa

我可以更换电话:

ssh-keygen -p -P 123456 -N "" -f /tmp/rsa

使用python加密模块:

from cryptography.hazmat.backends import default_backend
import cryptography.hazmat.primitives.serialization as crypto_serialization


priv_key = crypto_serialization.load_pem_private_key(open(key_path,"rb").read(),passphrase.encode('utf-8'),default_backend()
                                                     )
with open(key_path,"wb") as dest_pem:
    dest_pem.write(priv_key.private_bytes(crypto_serialization.Encoding.PEM,crypto_serialization.PrivateFormat.TraditionalOpenSSL,crypto_serialization.NoEncryption()
                                         )
                   )

但是当我使用参数 -t ed25519 生成密钥时,出现错误

  File "/usr/local/lib64/python3.6/site-packages/cryptography/hazmat/primitives/serialization/base.py",line 16,in load_pem_private_key
    return backend.load_pem_private_key(data,password)
  File "/usr/local/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py",line 1089,in load_pem_private_key
    password,File "/usr/local/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py",line 1315,in _load_key
    self._handle_key_loading_error()
  File "/usr/local/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py",line 1373,in _handle_key_loading_error
    raise ValueError("Could not deserialize key data.")
ValueError: Could not deserialize key data.

我使用 python paramiko 模块加载 Ed25519 私钥,但我无法序列化私有字节:

import paramiko
key_priv = paramiko.Ed25519Key.from_private_key_file('ed25519',password=b'123456')

解决方法

生成密钥对:

ssh-keygen -t ed25519 -N 123456 -f ed25519

使用 load_ssh_private_key 方法我尝试解密私钥:

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

priv_key = serialization.load_ssh_private_key(open('ed25519','rb').read(),b'123456',default_backend())

with open('ed25519_py',wb') as dest_key:
    dest_key.write(priv_key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.OpenSSH,serialization.NoEncryption()
                                         )
                   )

没有错误发生,我得到了未加密的 openssh 格式的私钥文件。

另一方面,我使用 ssk-keygen 工具将私钥文件的密码更改为空:

ssh-keygen -p -P 123456 -N "" -f ed25519

因此,我有两个解密的密钥,不匹配

如何使用python获取匹配ssh-keygen调用结果的密钥?