【问题标题】:Import string RSA public key to use RSA encryption in Go导入字符串 RSA 公钥以在 Go 中使用 RSA 加密
【发布时间】:2018-05-02 23:38:35
【问题描述】:

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

然后您可以使用 publicKey 和 RSA 进行加密。

【问题讨论】:

标签: go encryption rsa


【解决方案1】:

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

base64.StdEncoding.DecodeString("FExEiYPgwrHHyO7DOwCXHNRvVF2S8xirXftuFWmJUzo=")

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

【讨论】:

    猜你喜欢
    • 2014-10-29
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2021-03-30
    • 2018-01-13
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多