How to find the components of an ASN.1 EC python cryptography key

I generate an EC key using the python cryptography module this way

from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec key=ec.generate_private_key(ec.SECP256R1(), default_backend()) 

The structure of the ASn.1 EC key is as follows

  ECPrivateKey ::= SEQUENCE { version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), privateKey OCTET STRING, parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, publicKey [1] BIT STRING OPTIONAL } 

from https://tools.ietf.org/html/rfc5915 setion 3.

My question is how to get ASN.1 components from this key. I want to convert the key object to the OpenSSH private key, something like

 -----BEGIN EC PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,9549ED842979FDAF5299BD7B0E25B384 Z+B7I6jfgC9C03Kcq9rbWKo88mA5+YqxSFpnfRG4wkm2eseWBny62ax9Y1izGPvb J7gn2eBjEph9xobNewgPfW6/3ZDw9VGeaBAYRkSolNRadyN2Su6OaT9a2gKiVQi+ mqFeJmxsLyvew9XPkZqQIjML1d1M3T3oSA32zYX21UY= -----END EC PRIVATE KEY----- 

It is easy to handle DSA or RSA because all ASN.1 parameters are integers.

thanks in advance

+5
source share
1 answer

It is relatively easy to extract a public point from an ASN.1 sequence using pyasn1 , but if you want PEM-encrypted PKCS1 (aka "traditional OpenSSL"), then pyca / cryptography can do this quite easily:

 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ec backend = default_backend() key = ec.generate_private_key(ec.SECP256R1(), backend) serialized_key = key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.BestAvailableEncryption(b"my_great_password") ) 

You can find more information about private_bytes in the documentation. At this time, BestAvailableEncryption will be encrypted using AES-256-CBC .

0
source

All Articles