dongzuo4666 2018-02-25 02:58
浏览 332
已采纳

RSA密钥导出和导入

I'm currently trying to export my created keys and than importing them to use them.

But if I run my code I get the following error:

panic: x509: only RSA and ECDSA public keys supported

goroutine 1 [running]:
main.main()
    /path/to/project/src/main.go:19 +0x3bd

This is my current code:

// Create key
key, _ := rsa.GenerateKey(rand.Reader, 2048)

// Message to encrypt
message := "hi stackoverflow"

priv := x509.MarshalPKCS1PrivateKey(key)
pub, err := x509.MarshalPKIXPublicKey(key.PublicKey)
if err != nil {
    panic(err)
}

private, err := x509.ParsePKCS1PrivateKey(priv)
if err != nil {
    panic(err)
    return
}

public, err := x509.ParsePKIXPublicKey(pub)
if err != nil {
    return
}

encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, public.(*rsa.PublicKey), []byte(message))
if err != nil {
    panic(err)
}
dencrypted, err := rsa.DecryptPKCS1v15(rand.Reader, private, encrypted)
if err != nil {
    panic(err)
}
fmt.Println(string(dencrypted))

(I researched like the hole internet but didn't found something, maybe I used a wrong search term.)

  • 写回答

1条回答 默认 最新

  • doujiao1905 2018-02-25 17:32
    关注

    When I run this, I get the panic on MarshalPKIXPublicKey (not ParsePKIXPublicKey as you were suggesting in comment above).

    The problem is that the function accepts a *rsa.PublicKey and you're passing a plain rsa.PublicKey.

    This works for me: pub, err := x509.MarshalPKIXPublicKey(&key.PublicKey).

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失