【问题标题】:How to use key pair generated by openpgp in go如何在go中使用openpgp生成的密钥对
【发布时间】:2021-03-23 16:03:48
【问题描述】:

我正在尝试使用 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())
}

【问题讨论】:

  • 你必须使用空白导入_ "golang.org/x/crypto/ripemd160"
  • 很奇怪,文档说不推荐使用ripemd160。 Opengpg 不应该默认使用 sha256 吗?

标签: go rsa openpgp


【解决方案1】:

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

TL;博士

TS;博士

由于官方的“golang.org/x/crypto/openpgp”包已被冻结和弃用,只要我们使用“golang.org/x/crypto/openpgp”包,目前看来唯一的解决方法就是:

  1. 降级Go版本和包,然后空白导入“_ golang.org/x/crypto/ripemd160”为@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 get 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

【讨论】:

  • 经过一番研究,我也使用了质子的叉子,但忘记更新我的帖子。感谢您清晰而有帮助的回复!
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 2018-08-02
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
相关资源
最近更新 更多