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.)
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)
.