Go - Golang openpg - Create Key pair and create signature

…衆ロ難τιáo~ 提交于 2019-12-05 15:56:01

Maybe this will do what you want. Disclaimer: I am not an expert in openpgp; I don't know whether this is correct or not. But it does work with gpg --import.

package main

import (
        "fmt"
        "os"

        "golang.org/x/crypto/openpgp"
        "golang.org/x/crypto/openpgp/armor"
)

func main() {
        var e *openpgp.Entity
        e, err := openpgp.NewEntity("itis", "test", "itis@itis3.com", nil)
        if err != nil {
                fmt.Println(err)
                return
        }

        // Add more identities here if you wish

        // Sign all the identities
        for _, id := range e.Identities {
                err := id.SelfSignature.SignUserId(id.UserId.Id, e.PrimaryKey, e.PrivateKey, nil)
                if err != nil {
                        fmt.Println(err)
                        return
                }
        }

        w, err := armor.Encode(os.Stdout, openpgp.PublicKeyType, nil)
        if err != nil {
                fmt.Println(err)
                return
        }
        defer w.Close()

        e.Serialize(w)
}

I wrote https://github.com/alokmenghrajani/gpgeez for exactly this purpose. It's a Go library which makes things like key creating or exporting a key as an armored string easier.

Here is the gist of it, without any error checking:

func CreateKey() *openpgp.Entity {
  key, _ := openpgp.NewEntity(name, comment, email, nil)

  for _, id := range key.Identities {
    id.SelfSignature.PreferredSymmetric = []uint8{...}    
    id.SelfSignature.PreferredHash = []uint8{...}    
    id.SelfSignature.PreferredCompression = []uint8{...}

    id.SelfSignature.SignUserId(id.UserId.Id, key.PrimaryKey, key.PrivateKey, nil)
  }

  // Self-sign the Subkeys
  for _, subkey := range key.Subkeys {
    subkey.Sig.SignKey(subkey.PublicKey, key.PrivateKey, nil)
  }

  return r
}

This seems to be a known issue: https://github.com/golang/go/issues/6483. The workaround is to call SerializePrivate first, even if you don't use the result.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!