Skip to content

Instantly share code, notes, and snippets.

@rphillips
Last active August 29, 2015 14:05
Show Gist options
  • Save rphillips/e70a9c22f22ade8b6998 to your computer and use it in GitHub Desktop.
Save rphillips/e70a9c22f22ade8b6998 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"io"
"os"
"os/user"
"path"
"strings"
"github.com/coreos/etcd/third_party/github.com/coreos/go-log/log"
"code.google.com/p/go.crypto/openpgp"
"code.google.com/p/go.crypto/openpgp/armor"
"code.google.com/p/gopass"
)
func getKeyByEmail(keyring openpgp.EntityList, email string) *openpgp.Entity {
for _, entity := range keyring {
for _, ident := range entity.Identities {
if ident.UserId.Email == email {
return entity
}
}
}
return nil
}
func expandPath(p string) (string, error) {
if path.IsAbs(p) {
return p, nil
}
if p[:2] == "~/" {
usr, err := user.Current()
if err != nil {
return "", err
}
p = strings.Replace(p, "~", usr.HomeDir, 1)
}
return p, nil
}
var secringPath = "~/.gnupg/secring.gpg"
var prompt = "password: "
func decryptFile(recipient, password, filePath string, privring openpgp.EntityList) {
secfile, err := os.Open(filePath)
if err != nil {
log.Error(err)
return
}
block, err := armor.Decode(secfile)
if err != nil {
log.Error(err)
return
}
count := 0
recipientEntity := getKeyByEmail(privring, recipient)
ents := openpgp.EntityList([]*openpgp.Entity{recipientEntity})
promptCallback := func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
count++
if count > 1 {
return nil, errors.New("Incorrect passphrase")
}
for _, k := range keys {
err := k.PrivateKey.Decrypt([]byte(password))
if err == nil {
return nil, nil
}
}
return nil, errors.New("invalid password or no private key")
}
md, err := openpgp.ReadMessage(block.Body, ents, promptCallback, nil)
if err != nil {
log.Error(err)
return
}
io.Copy(os.Stdout, md.UnverifiedBody)
}
func main() {
secringPath, _ = expandPath(secringPath)
privringFile, err := os.Open(secringPath)
if err != nil {
log.Error(err)
return
}
privring, err := openpgp.ReadKeyRing(privringFile)
if err != nil {
log.Error(err)
return
}
password, err := gopass.GetPass(prompt)
if err != nil {
log.Error(err)
return
}
decryptFile("[email protected]", password, "github-accounts.gpg", privring)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment