5

I trying to accomplish step (2) in the following way programmatically:

1. openssl genrsa -out signing.pem 2048
2. openssl rsa -in signing.pem -outform PEM -pubout -out signing.pub.pem

Following is a simple function which reads the private key and tries to extract the public key.

But, I am facing difficulty in matching the 2nd step, as the programmatically generated public key is different from the openssl CLI based public key, I am sure there must some mistake, Please, help me.

Thanks

   func main() {
    priv, err := ioutil.ReadFile("signing.pem")

    block, _ := pem.Decode([]byte(priv))
    if block == nil || block.Type != "RSA PRIVATE KEY" {
        log.Fatal("failed to decode PEM block containing public key")
    }
    key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        log.Fatal(err)
    }

    publicKeyDer := x509.MarshalPKCS1PublicKey(&pub.PublicKey)
    pubKeyBlock := pem.Block{
        Type:    "PUBLIC KEY",
        Headers: nil,
        Bytes:   publicKeyDer,
    }
    pubKeyPem := string(pem.EncodeToMemory(&pubKeyBlock))
    fmt.Println(pubKeyPem)
}

IN case anyone wants to check the code and play around then here's the link:

https://play.golang.org/p/rKerkh-31KI

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Invictus
  • 2,653
  • 8
  • 31
  • 50

1 Answers1

4

Use MarshalPKIXPublicKey

publicKeyDer, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
    log.Fatal(err)
}

Instead of

publicKeyDer := x509.MarshalPKCS1PublicKey(&key.PublicKey)

Playground

ssemilla
  • 3,900
  • 12
  • 28