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:
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.
When you receive the base64 encoded password your decode like:
base64.StdEncoding.DecodeString("FExEiYPgwrHHyO7DOwCXHNRvVF2S8xirXftuFWmJUzo=")
Then the string you encrypt must be no longer than the length of the public modulus minus twice the hash length, minus 2. See docs for examples and documentation.