在磁盘上保存并加载crypto / rsa PrivateKey [英] Save and load crypto/rsa PrivateKey to and from the disk
问题描述
我正在使用 crypto / rsa
,并试图找到正确保存并加载密钥的方法。是否有正确的方法从 rsa.PrivateKey
创建 [] byte
>。如果是这样的话,有没有办法正确地做到这一点: rsa.PublicKey
?
I'm using crypto/rsa
, and trying to find a way to properly save and load a key. Is there a correct way to create a []byte
from an rsa.PrivateKey
. If so, is there a way to properly do so for an rsa.PublicKey
?
非常感谢大家。
推荐答案
你需要某种格式来编组密钥。 Go标准库支持的格式如下: http://golang.org/pkg / crypto / x509 /#MarshalPKCS1PrivateKey
You need some sort of format to marshal the key into. One format supported by the Go standard library can be found here: http://golang.org/pkg/crypto/x509/#MarshalPKCS1PrivateKey
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
反函数是 http://golang.org/pkg/crypto/x509/#ParsePKCS1PrivateKey 。
The inverse function is http://golang.org/pkg/crypto/x509/#ParsePKCS1PrivateKey.
func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)
但是,将编组密钥编码为PEM文件相对比较标准。
However, it is relatively standard to encode the marshaled key into a PEM file.
pemdata := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
},
)
您可以找到一个完整的示例这里。
You can find a full example here.
这篇关于在磁盘上保存并加载crypto / rsa PrivateKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!