小编dow*_*owi的帖子

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

如何从 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)

然后您可以使用publicKey …

encryption rsa go

5
推荐指数
1
解决办法
3308
查看次数

标签 统计

encryption ×1

go ×1

rsa ×1