Reputation: 366
I am generating a EC key using python cryptography module in 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 asn.1 structure of 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://www.rfc-editor.org/rfc/rfc5915 setion 3.
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
-----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 with handling DSA or RSA because all the ASN.1 parameters are integers in that.
Thank You in advance
Upvotes: 5
Views: 1390
Reputation: 14089
It's relatively easy to extract the public point from the ASN.1 sequence using pyasn1, but if you want PEM-encrypted PKCS1 (aka "traditional OpenSSL") then pyca/cryptography can do that 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 the private_bytes method in the docs. At this time BestAvailableEncryption
will encrypt using AES-256-CBC
.
Upvotes: 1