Save and load crypto/rsa PrivateKey to and from the disk

前端 未结 4 1127
萌比男神i
萌比男神i 2021-01-30 10:13

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.P

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 10:58

    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
    

    The inverse function is http://golang.org/pkg/crypto/x509/#ParsePKCS1PrivateKey.

    func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)
    

    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.

提交回复
热议问题