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

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

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档