Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting the public key from the private key

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

like image 967
Invictus Avatar asked Nov 09 '18 06:11

Invictus


1 Answers

Use MarshalPKIXPublicKey

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

Instead of

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

Playground

like image 182
ssemilla Avatar answered Oct 09 '22 04:10

ssemilla