How can I import an RSA public key from a string in Go, so that it can be used to encrypt data ?
My program should do the following:
- Receives a public key encoded in base64
- Decode this public key from base64 to bytes
- Import that public key so that it is usable by the RSA implementation of Go (Problem is at this stage)
-
Encrypt an AES key with:
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, plaintextBytes, []byte(""))
Thank you in advance !
SOLUTION:
The public key has to be decoded with the crypto/x509 package.
For example:
publicKeyInterface, err := x509.ParsePKIXPublicKey(publicKeyDER)
if err != nil {
log.Println("Could not parse DER encoded public key (encryption key)")
return []byte(""), err
}
publicKey, isRSAPublicKey := publicKeyInterface.(*rsa.PublicKey)
if !isRSAPublicKey {
log.Println("Public key parsed is not an RSA public key")
return []byte(""), err
}
You can then use the publicKey
with RSA to encrypt.