首页 > 解决方案 > 如何在go中使用openpgp生成的密钥对

问题描述

我正在尝试使用 openpgp lib 生成密钥对,当我想通过加密测试字符串来测试它时,它返回以下错误openpgp: invalid argument: cannot encrypt because no candidate hash functions are compiled in. (Wanted RIPEMD160 in this case.)。但是,当我传递从 gpg 导出的公钥时,它会起作用。

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

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

    e, _ = openpgp.NewEntity("testUser", "test", "test@test.test", 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())
}

标签: gorsaopenpgp

解决方案


我有完全相同的错误。

TL; 博士

TS; 博士

由于官方的 " golang.org/x/crypto/openpgp" 包已被冻结和弃用,只要我们使用 " golang.org/x/crypto/openpgp" 包,目前唯一的解决方法似乎是要么;

  1. 降级 Go 版本和包,然后_ golang.org/x/crypto/ripemd160像 @mh-cbon提到的那样空白导入“” 。
  2. 自己修补被拒绝的 PR。(因x/crypto/openpgp包裹被冻结而被拒绝)

但是我必须在 Go 1.16.6 上实现一个 OpenPGP 密钥对生成器。不要问为什么...

所以,我目前的替代方案是使用分叉包。这是Go 团队作为示例提到的大量分支之一

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

参考

  1. " x/crypto/openpgp: 标记为冻结和弃用" | 问题 #44226 | 走 | golang@GitHub
  2. " x/crypto/openpgp: 默认情况下不能加密新实体" | 问题 #37646 | 走 | golang@GitHub
  3. " x/crypto/openpgp: 默认情况下不能加密新实体" | 问题 #12153 | 走 | golang@GitHub

推荐阅读