【发布时间】: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 进行加密。
【问题讨论】:
-
请参考How to ask a good question? 您能否提供更多到目前为止您已经尝试过的代码?重现问题。
-
请提供您遇到的问题的minimal reproducible example。
标签: go encryption rsa