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.)
我目前正在尝试导出自己创建的密钥,而不是导入以使用它们。 p>
但是如果我运行我的代码,则会出现以下错误: p>
panic:x509:仅支持RSA和ECDSA公钥
goroutine 1 [正在运行] :
main.main()
/path/to/project/src/main.go:19 + 0x3bd
code> pre>
这是我当前的代码: p>
//创建密钥
key,_:= rsa.GenerateKey(rand.Reader,2048)
//要加密的消息
message:=“ hi stackoverflow” \ n
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)
} \ ndencrypted,err:= rsa.Decry ptPKCS1v15(rand.Reader,私有,加密)
if err!= nil {
panic(err)
}
fmt.Println(string(dencrypted))
code> pre>
(我像漏洞互联网一样进行研究,但没有发现任何东西,也许我使用了错误的搜索词。) p>
div>
答
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)
.