导入字符串RSA公钥以在Go中使用RSA加密

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.

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.