Home > database >  How to create .der file in golang same as openssl do
How to create .der file in golang same as openssl do

Time:12-07

"openssl rsa -in prevate.pem -outform DER -pubout -out public.der"

CodePudding user response:

You might consider a library like google/trillian, which does include a MustMarshalPublicPEMToDER(keyPEM string) []byte function.

// MustMarshalPublicPEMToDER reads a PEM-encoded public key and returns it in DER encoding.
// If an error occurs, it panics.
func MustMarshalPublicPEMToDER(keyPEM string) []byte {
    block, _ := pem.Decode([]byte(keyPEM))
    key, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        panic(err)
    }

    keyDER, err := x509.MarshalPKIXPublicKey(key)
    if err != nil {
        panic(err)
    }
    return keyDER
}

As the comment of this function shows, this reads a PEM-encoded public key.

As noted by Topaco, you would need crypto/x509#ParsePKCS8PrivateKey in order to read a private PKCS#8 PEM encoded key.
The marshal part does not change.

  • Related