I have a ECDSA private key, which needs to be converted to PKCS8 DER. For now I use a Python script, but I want to use bash with openssl or node.js for further AWS KMS import.
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from dotenv import load_dotenv
import os
private_key_hex = "******"
def load_private_key_from_hex(private_key_hex):
# Convert the hex string to bytes
private_key_bytes = bytes.fromhex(private_key_hex)
# Generate the private key object from the bytes
private_key = ec.derive_private_key(
int.from_bytes(private_key_bytes, byteorder='big'),
ec.SECP256K1(),
default_backend()
)
return private_key
def convert_key_to_der_format(private_key):
der_private_key = private_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
return der_private_key
private_key = load_private_key_from_hex(private_key_hex)
der_private_key = convert_key_to_der_format(private_key)
with open("...", "wb") as der_file:
der_file.write(der_private_key)