【问题标题】:open a password protected .pem and .crt file using python使用 python 打开受密码保护的 .pem 和 .crt 文件
【发布时间】:2022-11-17 22:55:44
【问题描述】:

我使用命令创建了一个私钥和公钥:

 .....
 openssl genrsa -aes256 -passout pass:password -out key.pem
 4096 &&
openssl rsa -in key.pem -passin pass:password -pubout -out 
 pukey.pub

然后使用此命令创建证书文件:

 openssl req -new -key key.pem -passin pass:password -x509 -out 
 keycert.pem -days 365000 -subj '/CN=localhost'

所以我用密码保护了 key.pem,我想在我的 python 程序中打开它,如何指定打开 key.pem 文件和 keycert.pem 文件的密码?

with open('../key.pem', 'rb') as f:
   private_key = f.read()
with open('../keycert.pem', 'rb') as f:
   certificate_chain = f.read()
   

当我运行它时出现错误:

E1117 13:57:03.515461744   70812 ssl_transport_security.cc:854] 
Invalid private key.

这表明它无法打开 key.pem 文件,因为它受密码保护

【问题讨论】:

  • 你如何使用密钥?只是打开和读取文件不应该引发错误。您可以使用 cryptography 包解码密钥。
  • 这回答了你的问题了吗? read certificate(.crt) and key(.key) file in python
  • 实际上现在我认为它会起作用:with open('key.pem', 'rb') as f: private_key=serilalization.load_pem_private_key(f.read(), password="1".encode(), backend=default_backend ()) 但我需要返回值在 Byte 中,而且这个方法的返回值似乎是 _RSAPrivateKey
  • 你知道如何在 python 中将 _RSAPrivateKey 转换为字节吗?

标签: python python-3.x


【解决方案1】:

使用这一行:

with open('key.pem', 'rb') as f:
    private_key=load_pem_private_key(f.read(), password="1".encode(),
                                              backend=default_backend())
    pem =private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
    )

解决了问题,首先加载私钥,然后将其转换为字节。

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 2021-10-08
    • 2020-08-29
    • 2013-10-27
    • 1970-01-01
    • 2018-10-01
    • 2013-07-14
    相关资源
    最近更新 更多