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

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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置