如何查找EC密钥python-cryptography的ASN.1组件

时间:2016-09-22 16:39:49

标签: python cryptography openssh python-cryptography

我正在以这种方式使用python加密模块生成EC密钥

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

EC密钥的asn.1结构如下

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

来自https://tools.ietf.org/html/rfc5915第3节。

我的问题是如何从此密钥获取ASN.1组件。我想将密钥对象转换为OpenSSH私钥,如

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

Z+B7I6jfgC9C03Kcq9rbWKo88mA5+YqxSFpnfRG4wkm2eseWBny62ax9Y1izGPvb
J7gn2eBjEph9xobNewgPfW6/3ZDw9VGeaBAYRkSolNRadyN2Su6OaT9a2gKiVQi+
mqFeJmxsLyvew9XPkZqQIjML1d1M3T3oSA32zYX21UY=
-----END EC PRIVATE KEY-----

处理DSA或RSA很容易,因为所有ASN.1参数都是整数。

提前谢谢

1 个答案:

答案 0 :(得分:1)

使用Generic htaccess redirect www to non-www从ASN.1序列中提取公共点相对容易,但如果您想要PEM加密的PKCS1(又名“传统OpenSSL”),那么pyca /加密可以很容易地做到:< / p>

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")
)

您可以在文档中找到有关pyasn1方法的更多信息。目前BestAvailableEncryption将使用AES-256-CBC加密。