golang - marshal PKCS8 private key?

前端 未结 2 1039
野的像风
野的像风 2021-01-13 03:45

Is there a way to marshal a PKCS8 private key in go 1.5?
e.g. something similar to or starting from x509.MarshalPKCS1PrivateKey?

相关标签:
2条回答
  • 2021-01-13 04:38

    Since the above answer was written, go 1.10 has been released with a x509.MarshalPKCS8PrivateKey method.

    0 讨论(0)
  • 2021-01-13 04:47

    Funny enough, there are no standard function to do that, but here is a custom solution:

    type pkcs8Key struct {
        Version             int
        PrivateKeyAlgorithm []asn1.ObjectIdentifier
        PrivateKey          []byte
    }
    
    
    func rsa2pkcs8(key *rsa.PrivateKey) ([]byte, error) {
        var pkey pkcs8Key
        pkey.Version = 0 
        pkey.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1)
        pkey.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
        pkey.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
    
        return asn1.Marshal(pkey)
    }
    
    0 讨论(0)
提交回复
热议问题