Home  >  Article  >  Backend Development  >  How to Marshal PKCS8 Private Keys in Go 1.5?

How to Marshal PKCS8 Private Keys in Go 1.5?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 16:41:30349browse

 How to Marshal PKCS8 Private Keys in Go 1.5?

Marshalling PKCS8 Private Key in Go

Can PKCS8 private keys be marshaled in Go 1.5? Specifically, is there a method akin to x509.MarshalPKCS1PrivateKey for PKCS8?

Solution:

Despite the absence of a standard function for this task, a custom solution is available:

<code class="go">import (
    "crypto/rsa"
    "crypto/asn1"
    "crypto/x509"
)

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

The above is the detailed content of How to Marshal PKCS8 Private Keys in Go 1.5?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn