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

dow*_*owi 5 encryption rsa go

如何从 Go 中的字符串导入 RSA 公钥,以便将其用于加密数据?

我的程序应该执行以下操作:

  • 接收以 base64 编码的公钥
  • 将此公钥从 base64 解码为字节
  • 导入该公钥,以便 Go 的 RSA 实现可以使用它(问题出现在这个阶段)
  • 使用以下方法加密 AES 密钥:

    ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, plaintextBytes, []byte(""))

先感谢您 !

解决方案

公钥必须使用crypto/x509包进行解码。

例如:

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
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用publicKeyRSA 进行加密。

小智 0

当您收到 Base64 编码的密码时,您的解码如下:

base64.StdEncoding.DecodeString("FExEiYPgwrHHyO7DOwCXHNRvVF2S8xirXftuFWmJUzo=")
Run Code Online (Sandbox Code Playgroud)

那么您加密的字符串不得长于公共模数的长度减去哈希长度的两倍,再负2。有关示例和文档,请参阅文档。