登录
首页 >  Golang >  Go问答

使用OpenPGP在Go语言中生成密钥对

来源:stackoverflow

时间:2024-02-18 17:27:22 184浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《使用OpenPGP在Go语言中生成密钥对》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我正在尝试使用 openpgp lib 生成密钥对,当我想通过加密测试字符串来测试它时,它返回以下错误 openpgp:无效参数:无法加密,因为没有编译候选哈希函数。(想要 ripemd160在这种情况下。)。但是,当我传递从 gpg 导出的公钥时,它会起作用。

另外我想知道如何像 gpg --generate-key 那样加密私钥?

func main() {
    var e *openpgp.Entity
    var pubKey *bytes.Buffer

    e, _ = openpgp.NewEntity("testUser", "test", "[email protected]", nil)

    for _, id := range e.Identities {
        err := id.SelfSignature.SignUserId(id.UserId.Id, e.PrimaryKey, e.PrivateKey, nil)

        if err != nil {
            fmt.Println(err)
            return
        }
    }

    buf := new(bytes.Buffer)
    w, err := armor.Encode(buf, openpgp.PublicKeyType, nil)

    if err != nil {
        fmt.Println(err)
        return
    }

    e.Serialize(w)
    w.Close()
    pubKey = buf

    // Encrypting test with public key 
    entity, err := openpgp.ReadArmoredKeyRing(pubKey)

    if err != nil {
        fmt.Println(err)
        return
    }

    buf = new(bytes.Buffer)

    encoderWriter, err := armor.Encode(buf, "PGP MESSAGE", make(map[string]string))

    if err != nil {
        fmt.Println(err)
        return
    }

    encryptorWriter, err := openpgp.Encrypt(encoderWriter, entity, nil, nil, nil)

    if err != nil {
        fmt.Println(err)
        return
    }

    encryptorWriter.Write([]byte("hello world"))
    encryptorWriter.Close()
    encoderWriter.Close()

    fmt.Println(buf.String())
}

解决方案


我遇到了完全相同的错误。

TL;博士

TS;博士

由于官方的“golang.org/x/crypto/openpgp”包被冻结并弃用,只要我们使用“golang.org/x/crypto/openpgp”包,似乎当前唯一的解决方法是到任一;

  1. 降级 Go 版本和软件包,然后空白 import "_ golang.org/x/crypto/ripemd160" as @mh-cbon mentioned
  2. 自行修补被拒绝的 PR。 (因 x/crypto/openpgp 包被冻结而被拒绝)

但我必须在 Go 1.16.6 上实现 OpenPGP 密钥对生成器。 别问为什么...

所以,我当前的选择是使用分叉包。这是 one of the abounding forks that the Go team mentioned as a sample

  • github.com/ProtonMail/go-crypto 包@ GitHub
    1. go 获取 github.com/ProtonMail/go-crypto
    2. go.mod 中删除 golang.org/x/crypto/openpgp
    3. 将源代码中的所有“golang.org/x/crypto/openpgp”替换为 “github.com/ProtonMail/go-crypto/openpgp”
    4. go mod tidy

参考文献

  1. x/crypto/openpgp: mark as frozen and deprecated”|问题#44226 |去 | golang@GitHub
  2. x/crypto/openpgp: new entities cannot be encrypted to by default”|问题#37646 |去 | golang@GitHub
  3. x/crypto/openpgp: new entities cannot be encrypted to by default”|问题#12153 |去 | golang@GitHub

好了,本文到此结束,带大家了解了《使用OpenPGP在Go语言中生成密钥对》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>