RSA 密钥导出和导入
RSA Key Export and Import
我目前正在尝试导出我创建的密钥,而不是导入它们以使用它们。
但是如果我 运行 我的代码会出现以下错误:
panic: x509: only RSA and ECDSA public keys supported
goroutine 1 [running]:
main.main()
/path/to/project/src/main.go:19 +0x3bd
这是我当前的代码:
// Create key
key, _ := rsa.GenerateKey(rand.Reader, 2048)
// Message to encrypt
message := "hi Whosebug"
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))
(我在网上搜索了很多东西,但没有找到任何东西,也许我使用了错误的搜索词。)
当我 运行 这样做时,我对 MarshalPKIXPublicKey
感到恐慌(不是你在上面评论中建议的 ParsePKIXPublicKey
)。
问题是该函数接受一个 *rsa.PublicKey
而你传递的是一个普通的 rsa.PublicKey
。
这对我有用:pub, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
。
我目前正在尝试导出我创建的密钥,而不是导入它们以使用它们。
但是如果我 运行 我的代码会出现以下错误:
panic: x509: only RSA and ECDSA public keys supported
goroutine 1 [running]:
main.main()
/path/to/project/src/main.go:19 +0x3bd
这是我当前的代码:
// Create key
key, _ := rsa.GenerateKey(rand.Reader, 2048)
// Message to encrypt
message := "hi Whosebug"
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))
(我在网上搜索了很多东西,但没有找到任何东西,也许我使用了错误的搜索词。)
当我 运行 这样做时,我对 MarshalPKIXPublicKey
感到恐慌(不是你在上面评论中建议的 ParsePKIXPublicKey
)。
问题是该函数接受一个 *rsa.PublicKey
而你传递的是一个普通的 rsa.PublicKey
。
这对我有用:pub, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
。