在 python 中将 EC 私钥从 PEM 转换为 DER
Converting EC private key from PEM to DER in python
我正在尝试编写一个 Python 脚本,使用 Python 中的 cryptography 将 EC 私钥从 PKCS8 PEM 转换为 DER。
我以前可以像这样使用 openssl 做到这一点:
openssl pkcs8 -nocrypt -in pem_key.p8 -out der_key.der -outform der
我通过以下操作验证使用 OpenSSL 生成的 DER 文件是否正确:
from ecdsa import SigningKey
file = open('der_key.der', 'rb')
SigningKey.from_der(file.read())
>>> <ecdsa.keys.SigningKey at 0x112bd3630>
现在我尝试使用 Python
做同样的事情
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
pem_key_bytes = str.encode(pem_key)
key = serialization.load_pem_private_key(
pem_key_bytes, password=None, backend=default_backend()
)
pri_der = key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
然而,当使用上述相同方法在 DER 编码中测试此密钥时,我得到:
UnexpectedDER: expected '1' at start of DER privkey, got 0
我错过了什么?
尝试使用不同的格式,例如 TraditionalOpenSSL
。这对我来说很合适。
pri_der = key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
我正在尝试编写一个 Python 脚本,使用 Python 中的 cryptography 将 EC 私钥从 PKCS8 PEM 转换为 DER。
我以前可以像这样使用 openssl 做到这一点:
openssl pkcs8 -nocrypt -in pem_key.p8 -out der_key.der -outform der
我通过以下操作验证使用 OpenSSL 生成的 DER 文件是否正确:
from ecdsa import SigningKey
file = open('der_key.der', 'rb')
SigningKey.from_der(file.read())
>>> <ecdsa.keys.SigningKey at 0x112bd3630>
现在我尝试使用 Python
做同样的事情from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
pem_key_bytes = str.encode(pem_key)
key = serialization.load_pem_private_key(
pem_key_bytes, password=None, backend=default_backend()
)
pri_der = key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
然而,当使用上述相同方法在 DER 编码中测试此密钥时,我得到:
UnexpectedDER: expected '1' at start of DER privkey, got 0
我错过了什么?
尝试使用不同的格式,例如 TraditionalOpenSSL
。这对我来说很合适。
pri_der = key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)