5

I am trying to write a Python script to convert an EC private key from PKCS8 PEM to DER using cryptography in Python.

I was able to do this previously using openssl like so:

openssl pkcs8 -nocrypt -in pem_key.p8 -out der_key.der -outform der

I verify that the DER file generated with OpenSSL is correct by doing:

from ecdsa import SigningKey
file = open('der_key.der', 'rb')

SigningKey.from_der(file.read())

>>> <ecdsa.keys.SigningKey at 0x112bd3630>

Now I attempt to do the same using 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(),
)

However when testing this key in DER encoding using the same method above I get:

UnexpectedDER: expected '1' at start of DER privkey, got 0

What am I missing?

Alfonso Embid-Desmet
  • 3,561
  • 3
  • 32
  • 45

1 Answers1

4

Try using a different format, like TraditionalOpenSSL. That made it for me.

pri_der = key.private_bytes(
    encoding=serialization.Encoding.DER,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption(),
)
MiguelCarranza
  • 246
  • 1
  • 7