doulongti5932 2018-11-09 06:56
浏览 219
已采纳

从私钥中提取公钥

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

  • 写回答

1条回答 默认 最新

  • doujuan2688 2018-11-09 07:41
    关注

    Use MarshalPKIXPublicKey

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

    Instead of

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

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波