使用Golang的crypto库如何编写ECDSA密钥?

huangapple go评论72阅读模式
英文:

How to write out ecdsa keys using golang crypto?

问题

我有一些Go代码用于生成ECDSA密钥并将其写入文件:

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

这段代码可以生成一个"BEGIN EC PRIVATE KEY"块。但是,当你在openssl中写出密钥时,还会得到一个指定所使用曲线的"BEGIN EC PARAMETERS"块。在Go中,有没有一种方法将EC PARAMETERS写入pem文件中呢?

英文:

I have some 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 out in openssl you also get a "BEGIN EC PARAMETERS" block specifying the curve used. Is there a way to write out the EC PARAMETERS to the pem file in Go?

答案1

得分: 8

到目前为止,我找到的一种丑陋的方法是:

对于命名曲线,openssl将ASN.1 OID写入EC PARAMETERS块中。所以我从http://www.ietf.org/rfc/rfc5480.txt查找了P256曲线的OID,并添加了以下代码:

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

这对于我的当前用例有效,但我不知道是否可以通用地实现这一点。

英文:

One ugly way I found so far to do it:

For named curves, openssl writes out the ASN.1 OID into the EC PARAMETERS block. So I looked up the OID for the P256 curve 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's possible to do this generically..

huangapple
  • 本文由 发表于 2014年6月4日 03:02:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/24022946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定