我正在尝试使用 Python 的加密模块加载使用 OpenSSL 生成的私钥。
openssl genrsa -out rootCA.key 4096
密钥生成为:
并将其加载为:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import load_der_private_key
import os
with open(os.getcwd() + '/rootCA.key', 'rb') as f:
der_data=bytes(f.read())
key = load_der_private_key(der_data, password=None, backend=default_backend())
print (key)
但我收到此错误:
File "loading_key.py", line 9, in <module>
key = load_der_private_key(der_data, password=None, backend=default_backend())
File "/usr/local/lib/python3.6/dist-packages/cryptography/hazmat/primitives/serialization/base.py", line 28, in load_der_private_key
return backend.load_der_private_key(data, password)
File "/usr/local/lib/python3.6/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 1080, in load_der_private_key
password,
File "/usr/local/lib/python3.6/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 1251, in _load_key
self._handle_key_loading_error()
File "/usr/local/lib/python3.6/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 1309, in _handle_key_loading_error
raise ValueError("Could not deserialize key data.")
ValueError: Could not deserialize key data.
有人可以帮忙吗?我似乎无法找出问题所在,因为它看起来很简单。我在模块中看不到cryptography
与此相关的任何其他命令,所以我不确定这是否是一种不正确的处理方式。
编辑:
出于参考目的,或者任何遇到类似问题的人,这就是最终解决方案的样子:
with open(os.getcwd() + '/rootCA.key', "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)