douzi7890 2018-07-24 04:10
浏览 1032
已采纳

Golang RSA加密,错误为“无法解析公钥”

I have a trouble when I just want to simply encrypt a short string.

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "fmt"
    "log"
)

func main() {

    var pwd = "1234"
    var pwdB = []byte(pwd)

    fmt.Println(pwd)
    fmt.Println(pwdB)

    const pemPublicKey = `-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALE0I2XX+IzlhIfBx2KoYqcxlEU23oje
PTJzJ7GoYyK4R5gCkWV6ltyLN5G+rNkfsAnTObqIJK+sQzcqmm9up88CAwEAAQ==
-----END PUBLIC KEY-----`

    fmt.Println(pemPublicKey)

    block, _ := pem.Decode([]byte(pemPublicKey))
    if block == nil {
        panic("failed to parse PEM block containing the public key")
    }
    fmt.Println(block)

    pkey, _ := x509.ParsePKCS1PublicKey(block.Bytes)
    if pkey == nil {
        panic("failed to parse public key")
    }

    fmt.Println(pkey)

    in, err := rsa.EncryptPKCS1v15(rand.Reader, pkey, pwdB)
    if err != nil {
        log.Fatalf("encrypt: %s", err)
    }

    fmt.Println(in)
}

playground link

The error is :

panic: failed to parse public key
goroutine 1 [running]:
main.main()
    /tmp/sandbox736400947/main.go:36 +0x4a0

It seems that is the process in Parsing the public key, but I don't know what have I done wrong... What should I do next? Thanks :(

  • 写回答

1条回答 默认 最新

  • douba6361 2018-07-24 06:19
    关注

    You need to use x509.ParsePKIXPublicKey, check the error returned by the Parse... function, and perform a type check to make sure it is a RSA key before using it.

    Your code would become:

    pkey, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        panic(err)
    }
    
    rsaKey, ok := pkey.(*rsa.PublicKey)
    if !ok {
        log.Fatalf("got unexpected key type: %T", pkey)
    }
    

    Please don't skip errors. In this case, ParsePKCS1PublicKey would have returned something along the lines of asn1: structure error: tags don't match ... which indicates a bad format.

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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)