Reputation: 41
const strPrivateKey = "30820b82020100300d06092a864886f70d010101050004820b6c30820b680201000282028100acfc585f43ca36ec2dddc518b5c7d1303b658faec58b634aff16ce4b7930b93a23517f8d9c8a260f4e2eb44b01da5b6588fefe63acb68c15677"
decoded, err := hex.DecodeString(strPrivateKey)
if err != nil {
return ""
}
privateKey, err := x509.ParsePKCS8PrivateKey(decoded)
if err != nil {
return ""
}
encypt, err := rsa.EncryptPKCS1v15(rand.Reader, &privateKey.PublicKey, data)
if err != nil {
fmt.Println(err)
return ""
}
privateKey.PublicKey undefined (type any has no field or method PublicKey)
Upvotes: 2
Views: 2798
Reputation: 41
*correct answer. I resolved privateKey.(rsa.PrivateKey)
decodedString, err := hex.DecodeString(utility.StrPrivateKey)
if err != nil {
return err
}
pkcs8PrivateKey, err := x509.ParsePKCS8PrivateKey(decodedString)
if err != nil {
return err
}
privateKey := pkcs8PrivateKey.(*rsa.PrivateKey)
Upvotes: 0
Reputation: 7475
According to the doc (https://pkg.go.dev/crypto/[email protected]#ParsePKCS8PrivateKey):
func ParsePKCS8PrivateKey(der []byte) (key any, err error)
... It returns a
*rsa.PrivateKey
, a*ecdsa.PrivateKey
, or aed25519.PrivateKey
. More types might be supported in the future.
You should use type assertion to check the type of the key:
switch privateKey := privateKey.(type) {
case *rsa.PrivateKey:
// ...
case *ecdsa.PrivateKey:
// ...
case ed25519.PrivateKey:
// ...
default:
panic("unknown key")
}
Since rsa.EncryptPKCS1v15
expects a *rsa.PublicKey
, your code can be written like this:
if privateKey, ok := privateKey.(*rsa.PrivateKey); ok {
encypt, err := rsa.EncryptPKCS1v15(rand.Reader, &privateKey.PublicKey, data)
}
BTW, the provided strPrivateKey
is invalid (encoding/hex: odd length hex string
). You can get some valid private keys from https://github.com/golang/go/blob/1c05968c9a5d6432fc6f30196528f8f37287dd3d/src/crypto/x509/pkcs8_test.go#L52-L124
Upvotes: 1