简体   繁体   English

从私钥中提取公钥

[英]Extracting the public key from the private key

I trying to accomplish step (2) in the following way programmatically: 我尝试以编程方式以下列方式完成步骤(2):

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. 但是,我在配对第二步时遇到困难,因为以编程方式生成的公钥与基于openssl CLI的公钥不同,我相信肯定会有一些错误,请帮助我。

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 https://play.golang.org/p/rKerkh-31KI

Use MarshalPKIXPublicKey 使用MarshalPKIXPublicKey

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

Instead of 代替

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

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM