doudou3213 2017-11-19 18:22
浏览 529

导入字符串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.

  • 写回答

1条回答 默认 最新

  • drra6593 2017-11-20 11:19
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用