How to write ecdsa keys using golang crypto?

I have a Go code to generate an ECDSA key and write it to a file:

priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) ecder, err := x509.MarshalECPrivateKey(priv) keypem, err := os.OpenFile("ec-key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) pem.Encode(keypem, &pem.Block{Type: "EC PRIVATE KEY", Bytes: ecder}) 

This works and generates a BEGIN EC PRIVATE KEY block. But when you write the key in openssl, you also get the "BEGIN EC PARAMETERS" block that defines the curve used. Is there a way to write EU PARAMETERS to a pem file in Go?

+6
source share
1 answer

One ugly way I've found so far:

For named curves, openssl writes the OID of ASN.1 to the EC PARAMETERS block. So I searched for the OID for curve P256 from http://www.ietf.org/rfc/rfc5480.txt and added:

 secp256r1, err := asn1.Marshal(asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}) pem.Encode(keypem, &pem.Block{Type: "EC PARAMETERS", Bytes: secp256r1}) 

This works for my current use case, but I don't know if it is possible to do this in the general case.

+5
source

Source: https://habr.com/ru/post/970265/


All Articles