How to find ASN.1 components of EC key python-cryptography
<p>I am generating a EC key using python cryptography module in this way</p>

<pre><code>from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
key=ec.generate_private_key(ec.SECP256R1(), default_backend())
</code></pre>

<p>The asn.1 structure of EC key is as follows</p>

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

<p>from <a href="https://tools.ietf.org/html/rfc5915">https://tools.ietf.org/html/rfc5915</a> setion 3.</p>

<p>my question is how to get the ASN.1 components from this key. I want to convert the key object to OpenSSH private key, something like</p>

<pre><code>-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,9549ED842979FDAF5299BD7B0E25B384

Z+B7I6jfgC9C03Kcq9rbWKo88mA5+YqxSFpnfRG4wkm2eseWBny62ax9Y1izGPvb
J7gn2eBjEph9xobNewgPfW6/3ZDw9VGeaBAYRkSolNRadyN2Su6OaT9a2gKiVQi+
mqFeJmxsLyvew9XPkZqQIjML1d1M3T3oSA32zYX21UY=
-----END EC PRIVATE KEY-----
</code></pre>

<p>It is easy with handling DSA or RSA because all the ASN.1 parameters are integers in that.</p>

<p>Thank You in advance</p>

<p>It's relatively easy to extract the public point from the ASN.1 sequence using <a href="https://pypi.python.org/pypi/pyasn1" rel="nofollow">pyasn1</a>, but if you want PEM-encrypted PKCS1 (aka "traditional OpenSSL") then pyca/cryptography can do that quite easily:</p>

<pre><code>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")
)
</code></pre>

<p>You can find more information about the <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/#cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKeyWithSerialization.private_bytes" rel="nofollow">private_bytes</a> method in the docs. At this time <code>BestAvailableEncryption</code> will encrypt using <code>AES-256-CBC</code>.</p>

python cryptography openssh python-cryptography