Beispiel #1
0
func main() {
	pubRingFile, _ := os.Open("/home/brad/.gnupg/pubring.gpg")
	pubRing, _ := openpgp.ReadKeyRing(pubRingFile)
	privRingFile, _ := os.Open("/home/brad/.gnupg/secring.gpg")
	privRing, _ := openpgp.ReadKeyRing(privRingFile)
	myPrivateKey := getKeyByEmail(privRing, "*****@*****.**")
	theirPublicKey := getKeyByEmail(pubRing, "*****@*****.**")
	w, _ := armor.Encode(os.Stdout, "PGP MESSAGE", nil)
	plaintext, _ := openpgp.Encrypt(w, []*openpgp.Entity{theirPublicKey}, myPrivateKey, nil)
	fmt.Fprintf(plaintext, "Hello from golang.\n")
	plaintext.Close()
	w.Close()
	fmt.Printf("\n")
}
Beispiel #2
0
func processSecretKeyRing() (entity *openpgp.Entity, entitylist openpgp.EntityList) {
	// Get default secret keyring location
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	jaegerSecretKeyRing := fmt.Sprintf("%v/.gnupg/jaeger_secring.gpg", usr.HomeDir)
	secretKeyRing := ""

	if _, err := os.Stat(jaegerSecretKeyRing); err == nil {
		secretKeyRing = jaegerSecretKeyRing
	} else {
		secretKeyRing = fmt.Sprintf("%v/.gnupg/secring.gpg", usr.HomeDir)
	}

	debug.Printf("secretKeyRing file:", secretKeyRing)
	secretKeyRingBuffer, err := os.Open(secretKeyRing)
	if err != nil {
		panic(err)
	}
	entitylist, err = openpgp.ReadKeyRing(secretKeyRingBuffer)
	if err != nil {
		log.Fatal(err)
	}

	entity = entitylist[0]
	debug.Printf("Private key default keyring:", entity.Identities)

	return entity, entitylist
}
Beispiel #3
0
func encrypt(ringPath string, input io.Reader, output io.Writer) error {
	ringFile, err := os.Open(ringPath)
	if err != nil {
		return err
	}
	defer ringFile.Close()

	ring, err := openpgp.ReadKeyRing(ringFile)
	if err != nil {
		return err
	}
	// TODO: Select proper key
	key := ring[0]

	plaintext, err := openpgp.Encrypt(output, []*openpgp.Entity{key}, nil, nil, nil)
	if err != nil {
		return err
	}
	defer plaintext.Close()

	if _, err := io.Copy(plaintext, input); err != nil {
		return err
	}

	return nil
}
Beispiel #4
0
func GetSigner(keyringPath string, id string) (*openpgp.Entity, error) {
	f, er := os.Open(keyringPath)
	if er != nil {
		return nil, er
	}
	defer f.Close()

	entities, err := openpgp.ReadKeyRing(f)
	if err != nil {
		return nil, err
	}
	for _, entity := range entities {
		switch {
		case entity.PrivateKey == nil:
			continue
		case !entity.PrivateKey.Encrypted:
			return entity, nil
		default:
			passphrase, err := PromptPassphrase(entity.PrivateKey)
			if err == nil {
				err = entity.PrivateKey.Decrypt(passphrase)
			}
			if err != nil {
				fmt.Fprintf(os.Stderr, "could not decrypt private key: %s\n", err)
				continue
			}
			return entity, nil
		}
	}
	return nil, fmt.Errorf("no suitable private key found")
}
Beispiel #5
0
func (fe *FileEntityFetcher) FetchEntity(keyId string) (*openpgp.Entity, error) {
	f, err := wkfs.Open(fe.File)
	if err != nil {
		return nil, fmt.Errorf("jsonsign: FetchEntity: %v", err)
	}
	defer f.Close()
	el, err := openpgp.ReadKeyRing(f)
	if err != nil {
		return nil, fmt.Errorf("jsonsign: openpgp.ReadKeyRing of %q: %v", fe.File, err)
	}
	for _, e := range el {
		pubk := &e.PrivateKey.PublicKey
		if pubk.KeyIdString() != keyId {
			continue
		}
		if e.PrivateKey.Encrypted {
			if err := fe.decryptEntity(e); err == nil {
				return e, nil
			} else {
				return nil, err
			}
		}
		return e, nil
	}
	return nil, fmt.Errorf("jsonsign: entity for keyid %q not found in %q", keyId, fe.File)
}
Beispiel #6
0
func InitDocumentHandler(defs UploadDefs) {

	// initialize upload handling parameters
	uploadPath = defs.Path
	treshold = defs.ShareTreshold

	// check for disabled secret sharing scheme
	if treshold > 0 {
		// compute prime: (2^512-1) - SharePrimeOfs
		one := big.NewInt(1)
		ofs := big.NewInt(int64(defs.SharePrimeOfs))
		prime = new(big.Int).Lsh(one, 512)
		prime = new(big.Int).Sub(prime, one)
		prime = new(big.Int).Sub(prime, ofs)

		// open keyring file
		rdr, err := os.Open(defs.Keyring)
		if err != nil {
			// can't read keys -- terminate!
			logger.Printf(logger.ERROR, "[sid.upload] Can't read keyring file '%s' -- terminating!\n", defs.Keyring)
			os.Exit(1)
		}
		defer rdr.Close()

		// read public keys from keyring
		if reviewer, err = openpgp.ReadKeyRing(rdr); err != nil {
			// can't read keys -- terminate!
			logger.Printf(logger.ERROR, "[sid.upload] Failed to process keyring '%s' -- terminating!\n", defs.Keyring)
			os.Exit(1)
		}
	} else {
		logger.Printf(logger.WARN, "[sid.upload] Secret sharing scheme disabled -- uploads will be stored unencrypted!!")
	}
}
Beispiel #7
0
func runShowKey(cmd *Command, args []string) {
	var err error

	log := NewTee("postcrypt")
	path, _ := cmd.Config.GetString("main", "keyring")

	if len(args) < 1 {
		log.Err("too few arguments. run `go help " + cmd.Name + "`.")
		return
	}

	// open gpg keyring file
	fh, _ := os.Open(path)
	if err != nil {
		log.Crit("could not open keyring: " + err.Error())
		return
	}

	// read keyring
	keyring, err := openpgp.ReadKeyRing(fh)
	if err != nil {
		log.Crit("could not read keyring: " + err.Error())
		return
	}

	for _, entity := range keyring {
		if args[0] == getKeyId(entity) {
			fmt.Printf("%s:\n", getKeyId(entity))
			for _, ident := range entity.Identities {
				fmt.Printf("\t%s\n", ident.Name)
			}
		}
	}
}
Beispiel #8
0
func findKey(key string) (*openpgp.Entity, error) {
	keyId, err := strconv.ParseUint(key, 16, 64)
	if err != nil {
		log.Printf("Unable to parse key '%s': %s\n", key, err)
		return nil, &UnknownKey{key}
	}
	f, err := os.Open(KeyringFile)
	if err != nil {
		log.Printf("Failed to open keyring: %s\n", err)
		return nil, err
	}
	defer f.Close()
	el, err := openpgp.ReadKeyRing(f)
	if err != nil {
		log.Printf("Failed to read keyring: %s\n", err)
		return nil, err
	}
	for _, entity := range el {
		if entity.PrimaryKey.KeyId&0xFFFFFFFF == keyId {
			return entity, nil
		}
		for _, key := range entity.Subkeys {
			if key.PublicKey.KeyId&0xFFFFFFFF == keyId {
				return entity, nil
			}
		}
	}
	return nil, &UnknownKey{key}
}
Beispiel #9
0
func main() {
	sigReader := strings.NewReader(sig)
	sigBlock, err := armor.Decode(sigReader)
	if err != nil {
		panic(err)
	}
	if sigBlock.Type != openpgp.SignatureType {
		panic("not a signature type")
	}

	dataReader := strings.NewReader(data)

	krfd, err := os.Open("/home/ulfr/.gnupg/pubring.gpg")
	if err != nil {
		panic(err)
	}
	defer krfd.Close()

	keyring, err := openpgp.ReadKeyRing(krfd)
	if err != nil {
		panic(err)
	}
	entity, err := openpgp.CheckDetachedSignature(
		keyring, dataReader, sigBlock.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("valid signature from key %s\n",
		hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
}
Beispiel #10
0
// Verify() checks the validity of a signature for some data,
// and returns a boolean set to true if valid and an OpenPGP Entity
func Verify(data string, signature string, keyring io.Reader) (valid bool, entity *openpgp.Entity, err error) {
	valid = false

	// re-armor signature and transform into io.Reader
	sigReader := strings.NewReader(reArmor(signature))

	// decode armor
	sigBlock, err := armor.Decode(sigReader)
	if err != nil {
		panic(err)
	}
	if sigBlock.Type != "PGP SIGNATURE" {
		err = fmt.Errorf("Wrong signature type '%s'", sigBlock.Type)
		panic(err)
	}

	// convert to io.Reader
	srcReader := strings.NewReader(data)

	// open the keyring
	ring, err := openpgp.ReadKeyRing(keyring)
	if err != nil {
		panic(err)
	}

	entity, err = openpgp.CheckDetachedSignature(ring, srcReader, sigBlock.Body)
	if err != nil {
		panic(err)
	}

	// we passed, signature is valid
	valid = true

	return
}
func processPublicKeyRing() (entity *openpgp.Entity, entitylist openpgp.EntityList) {
	// TODO: Handle a specified recipient
	// Get default public keyring location
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	jaegerPublicKeyRing := fmt.Sprintf("%v/.gnupg/jaeger_pubring.gpg", usr.HomeDir)
	publicKeyRing := ""

	if _, err := os.Stat(jaegerPublicKeyRing); err == nil {
		publicKeyRing = jaegerPublicKeyRing
	} else {
		publicKeyRing = fmt.Sprintf("%v/.gnupg/pubring.gpg", usr.HomeDir)
	}

	debug.Printf("publicKeyRing file:", publicKeyRing)
	publicKeyRingBuffer, err := os.Open(publicKeyRing)
	if err != nil {
		panic(err)
	}
	entitylist, err = openpgp.ReadKeyRing(publicKeyRingBuffer)
	if err != nil {
		log.Fatal(err)
	}

	entity = entitylist[0]
	debug.Printf("Public key default keyring:", entity.Identities)

	return entity, entitylist
}
Beispiel #12
0
// Sign signs a string with a key identified by a key fingerprint or an email address
func Sign(data, keyid string, secringFile io.Reader) (sig string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("pgp.Sign(): %v", e)
		}
	}()
	keyring, err := openpgp.ReadKeyRing(secringFile)
	if err != nil {
		err = fmt.Errorf("Keyring access failed: '%v'", err)
		panic(err)
	}

	// find the entity in the keyring
	var signer *openpgp.Entity
	found := false
	for _, entity := range keyring {
		fingerprint := strings.ToUpper(hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
		for _, ident := range entity.Identities {
			email := ident.UserId.Email
			if keyid == fingerprint || keyid == email {
				signer = entity
				found = true
				break
			}
		}
	}
	if !found {
		err = fmt.Errorf("Signer '%s' not found", keyid)
		panic(err)
	}

	// if private key is encrypted, attempt to decrypt it with the passphrase
	if signer.PrivateKey.Encrypted {
		// get private key passphrase
		signer, err = decryptEntity(signer)
		if err != nil {
			panic(err)
		}
	}

	// calculate signature
	out := bytes.NewBuffer(nil)
	message := bytes.NewBufferString(data)
	err = openpgp.ArmoredDetachSign(out, signer, message, nil)
	if err != nil {
		err = fmt.Errorf("Signature failed: '%v'", err)
		panic(err)
	}

	// convert the writer back to string
	sig, err = deArmor(out.String())
	if err != nil {
		err = fmt.Errorf("Error converting signature to string: '%v'", err)
		panic(err)
	}

	return
}
Beispiel #13
0
func main() {
	if len(os.Args) < 2 {
		fmt.Printf("usage:\t%s <FINGERPRINT>\nex: \t%s 02699C276B60F27FC55C329968D63477A392B6FA\n",
			os.Args[0], os.Args[0])
		os.Exit(1)
	}
	keyid := os.Args[1]
	data := "some random string to sign"
	secringFile, err := os.Open(FindHomedir() + "/.gnupg/secring.gpg")
	if err != nil {
		panic(err)
	}
	defer secringFile.Close()
	keyring, err := openpgp.ReadKeyRing(secringFile)
	if err != nil {
		err = fmt.Errorf("Keyring access failed: '%v'", err)
		panic(err)
	}

	// find the entity in the keyring
	var signer *openpgp.Entity
	found := false
	for _, entity := range keyring {
		fingerprint := strings.ToUpper(hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
		fmt.Println("reading key with fingerprint", fingerprint)
		if keyid == fingerprint {
			signer = entity
			found = true
			fmt.Println("found a match")
			break
		}
	}
	if !found {
		err = fmt.Errorf("No key found for ID '%s'", keyid)
		panic(err)
	}

	// if private key is encrypted, attempt to decrypt it with the cached passphrase
	// then try with an agent or by asking the user for a passphrase
	if signer.PrivateKey.Encrypted {
		// get private key passphrase
		signer, err = decryptEntity(signer)
		if err != nil {
			panic(err)
		}
	}

	// calculate signature
	out := bytes.NewBuffer(nil)
	message := bytes.NewBufferString(data)
	err = openpgp.ArmoredDetachSign(out, signer, message, nil)
	if err != nil {
		err = fmt.Errorf("Signature failed: '%v'", err)
		panic(err)
	}

	fmt.Printf("%s\n", out)
}
Beispiel #14
0
func decrypt(ringPath string, input io.Reader) (io.Reader, error) {
	ringFile, err := os.Open(ringPath)
	if err != nil {
		return nil, err
	}
	defer ringFile.Close()

	ring, err := openpgp.ReadKeyRing(ringFile)
	if err != nil {
		return nil, err
	}

	var keyToTry, attempt int
	var triedCache bool
	promptFunc := openpgp.PromptFunction(func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
		if keyToTry >= len(keys) {
			return nil, fmt.Errorf("no more keys to try")
		}
		if attempt > 2 {
			attempt = 0
			keyToTry++
			return nil, nil
		}
		defer func() { attempt++ }()

		key := keys[keyToTry]
		fingerprint := fmt.Sprintf("%X", key.PublicKey.Fingerprint)

		if !triedCache {
			triedCache = true
			if cachedPass, _ := passphrase.GetPassphrase(fingerprint, "", "", "", false, false); cachedPass != "" {
				if err := key.PrivateKey.Decrypt([]byte(cachedPass)); err == nil {
					return nil, nil
				}
			}
		}

		passphrase.ClearCachedPassphrase(fingerprint)
		prompt := ""
		description := fmt.Sprintf("Key %s; attempt %d", key.PublicKey.KeyIdShortString(), attempt+1)
		passwd, err := passphrase.GetPassphrase(fingerprint, prompt, description, "", true, false)
		if err != nil {
			return nil, err
		}
		key.PrivateKey.Decrypt([]byte(passwd))

		return nil, nil
	})

	msgDetails, err := openpgp.ReadMessage(input, ring, promptFunc, nil)
	if err != nil {
		return nil, err
	}

	return msgDetails.UnverifiedBody, nil
}
Beispiel #15
0
func checkGPG(file File) (state SigState, err error) {
	var signer *openpgp.Entity
	keypath := path.Join(os.Getenv("HOME"), "/.gnupg/pubring.gpg")
	keys, err := os.Open(keypath)
	if err != nil {
		fmt.Printf("Could not open public keyring at %s\n", keypath)
		os.Exit(2)
	}

	keyring, err := openpgp.ReadKeyRing(keys)

	if err != nil {
		fmt.Printf("Error reading public keyring: %s\n", err)
		os.Exit(2)
	}

	if *flagBin {
		signer, err = openpgp.CheckDetachedSignature(keyring, bytes.NewReader(file.content), bytes.NewReader(file.signature))
	} else {
		signer, err = openpgp.CheckArmoredDetachedSignature(keyring, bytes.NewReader(file.content), bytes.NewReader(file.signature))
	}
	if err != nil {
		fmt.Printf("Invalid signature or public key not present: %s\n", err)
		os.Exit(2)
	}

	state.sig = signer.PrimaryKey.KeyIdString()

	l := len(*flagKeyid)
	if l > 0 {
		var rid string

		// Force the local id to be all uppercase
		lid := strings.ToUpper(*flagKeyid)

		// check the number of chars on the remote id to see if it's a
		// short or long id. If it's not 8 or 16, it's not valid.
		switch l {
		case 8:
			rid = signer.PrimaryKey.KeyIdShortString()
		case 16:
			rid = signer.PrimaryKey.KeyIdString()
		}
		if len(rid) == 0 {
			fmt.Printf("You did not specify a valid GPG keyid length. Must be 8 or 16 characters.")
			os.Exit(2)
		}

		if lid != rid {
			fmt.Printf("The remote file was not signed by the expected GPG Public key. Expected %s and got %s\n", lid, rid)
			os.Exit(2)
		}
	}
	state.success = true
	return state, nil
}
Beispiel #16
0
func initCrypto(keyRingPath, pass string) {
	f, err := os.Open(keyRingPath)
	if err != nil {
		log.Fatalf("Can't open keyring: %v", err)
	}
	defer f.Close()

	keys, err = openpgp.ReadKeyRing(f)
	if err != nil {
		log.Fatalf("Can't read keyring: %v", err)
	}
}
Beispiel #17
0
func loadKeyringFile(path string) (openpgp.EntityList, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	el, err := openpgp.ReadKeyRing(f)
	if err != nil {
		return nil, err
	}
	return el, nil
}
Beispiel #18
0
func (g *GpgEncrypt) LoadPublicKeyRing() error {
	keyringFileBuffer, err := os.Open(g.PublicKeyringPath)
	if err != nil {
		return err
	}
	defer keyringFileBuffer.Close()
	entitylist, err := openpgp.ReadKeyRing(keyringFileBuffer)
	if err == nil {
		g.entityList = entitylist
	}
	return err
}
Beispiel #19
0
// KeyIdFromRing returns the public keyId contained in the secret
// ring file secRing. It expects only one keyId in this secret ring
// and returns an error otherwise.
func KeyIdFromRing(secRing string) (keyId string, err error) {
	f, err := wkfs.Open(secRing)
	if err != nil {
		return "", fmt.Errorf("Could not open secret ring file %v: %v", secRing, err)
	}
	defer f.Close()
	el, err := openpgp.ReadKeyRing(f)
	if err != nil {
		return "", fmt.Errorf("Could not read secret ring file %s: %v", secRing, err)
	}
	if len(el) != 1 {
		return "", fmt.Errorf("Secret ring file %v contained %d identities; expected 1", secRing, len(el))
	}
	ent := el[0]
	return ent.PrimaryKey.KeyIdShortString(), nil
}
Beispiel #20
0
func NewPwStore(keyring string) (*PwStore, error) {
	f, err := os.Open(keyring)
	if err != nil {
		return nil, err
	}

	keyr, err := openpgp.ReadKeyRing(f)
	if err != nil {
		return nil, err
	}

	ret := &PwStore{
		keyring: keyr,
	}
	return ret, nil
}
Beispiel #21
0
func main() {
	secringFile, err := os.Open("/tmp/testgolangopenpgp/secring.gpg")
	if err != nil {
		panic(err)
	}
	defer secringFile.Close()
	keyring, err := openpgp.ReadKeyRing(secringFile)
	if err != nil {
		err = fmt.Errorf("Keyring access failed: '%v'", err)
		panic(err)
	}
	fmt.Printf("found %d entities in keyring\n", len(keyring))
	for _, entity := range keyring {
		fingerprint := strings.ToUpper(hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
		fmt.Println("reading entity with fingerprint", fingerprint)
	}
}
func ReadKeyRing(path string) (*openpgp.EntityList, error) {
	var keys openpgp.EntityList
	var err error

	f, err := os.Open(path)
	if err != nil {
		return nil, NewPgpError(ERR_KEYRING, fmt.Sprintf("Unable to open gnupg keyring: %v", err))
	}
	defer f.Close()

	keys, err = openpgp.ReadKeyRing(f)
	if err != nil {
		return nil, NewPgpError(ERR_KEYRING, fmt.Sprintf("Unable to read from gnupg keyring: %v", err))
	}

	return &keys, nil
}
Beispiel #23
0
func initCrypto() {
	if *uploadEncryptTo == "" {
		return
	}

	// If encrypting, the hashes are basically not known.
	*uploadNoHash = true

	f, err := os.Open(filepath.Join(gpgHome(), "pubring.gpg"))
	if err != nil {
		log.Fatalf("Can't open keyring: %v", err)
	}
	defer f.Close()

	kl, err := openpgp.ReadKeyRing(f)
	if err != nil {
		log.Fatalf("Can't read keyring: %v", err)
	}

	keyids := strings.Split(*uploadEncryptTo, ",")
	var hprefs, sprefs []uint8

	for _, w := range keyids {
		for _, e := range kl {
			if e.PrimaryKey.KeyIdShortString() == w {
				pi := primaryIdentity(e)
				ss := pi.SelfSignature

				hprefs = intersectPref(hprefs, ss.PreferredHash)
				sprefs = intersectPref(sprefs, ss.PreferredSymmetric)
				encryptKeys = append(encryptKeys, e)
			}
		}
	}

	if len(encryptKeys) != len(keyids) {
		log.Fatalf("Couldn't find all keys")
	}
	if len(hprefs) == 0 {
		log.Fatalf("No common hashes for encryption keys")
	}
	if len(sprefs) == 0 {
		log.Fatalf("No common symmetric ciphers for encryption keys")
	}
}
Beispiel #24
0
func runListKeys(cmd *Command, args []string) {
	var err error
	var emails []string

	log := NewTee("postcrypt")
	path, _ := cmd.Config.GetString("main", "keyring")

	// open gpg keyring file
	fh, _ := os.Open(path)
	if err != nil {
		log.Crit("could not open keyring: " + err.Error())
		return
	}

	// read keyring
	keyring, err := openpgp.ReadKeyRing(fh)
	if err != nil {
		log.Crit("could not read keyring: " + err.Error())
		return
	}

	emails, _ = cmd.Config.GetOptions("keys")
	emails = append(emails, getAllEmails(keyring)...)

	fmt.Println("# Note: keys with (!!!) could not be found in keyring")

	for _, e := range emails {
		ids := getIdsByEmails(cmd.Config, keyring, []string{e})
		fmt.Printf("%s = ", e)
		for _, i := range ids {
			if len(getKeysByIds(keyring, []string{i})) > 0 {
				fmt.Printf("%s ", i)
			} else {
				fmt.Printf("%s(!!!) ", i)
			}
		}

		fmt.Printf("\n")
	}
}
Beispiel #25
0
func loadPGPKey(path string, defaultPath string) (*openpgp.Entity, error) {
	if path == "" {
		path = getHomePath(defaultPath)
	}
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	block, err := armor.Decode(f)
	if err != nil {
		return nil, err
	}
	el, err := openpgp.ReadKeyRing(block.Body)
	if err != nil {
		return nil, err
	}
	if len(el) != 1 {
		return nil, fmt.Errorf("Key file %s contained %d keys, expecting 1", path, len(el))
	}
	return el[0], nil
}
Beispiel #26
0
func getKeys(c *conf.ConfigFile, e Envelope) openpgp.EntityList {
	var ids []string
	var path string
	var fh *os.File
	var err error
	var k openpgp.EntityList

	path, _ = c.GetString("main", "keyring")

	fh, err = os.Open(path)
	if err != nil {
		panic(err)
	}

	k, err = openpgp.ReadKeyRing(fh)
	if err != nil {
		panic(err)
	}

	ids = getIdsByEmails(c, k, e.Recipients)
	return getKeysByIds(k, ids)
}
Beispiel #27
0
// EntityFromSecring returns the openpgp Entity from keyFile that matches keyId.
// If empty, keyFile defaults to osutil.SecretRingFile().
func EntityFromSecring(keyId, keyFile string) (*openpgp.Entity, error) {
	if keyId == "" {
		return nil, errors.New("empty keyId passed to EntityFromSecring")
	}
	keyId = strings.ToUpper(keyId)
	if keyFile == "" {
		keyFile = osutil.SecretRingFile()
	}
	secring, err := wkfs.Open(keyFile)
	if err != nil {
		return nil, fmt.Errorf("jsonsign: failed to open keyring: %v", err)
	}
	defer secring.Close()

	el, err := openpgp.ReadKeyRing(secring)
	if err != nil {
		return nil, fmt.Errorf("openpgp.ReadKeyRing of %q: %v", keyFile, err)
	}
	var entity *openpgp.Entity
	for _, e := range el {
		pk := e.PrivateKey
		if pk == nil || (pk.KeyIdString() != keyId && pk.KeyIdShortString() != keyId) {
			continue
		}
		entity = e
	}
	if entity == nil {
		found := []string{}
		for _, e := range el {
			pk := e.PrivateKey
			if pk == nil {
				continue
			}
			found = append(found, pk.KeyIdShortString())
		}
		return nil, fmt.Errorf("didn't find a key in %q for keyId %q; other keyIds in file = %v", keyFile, keyId, found)
	}
	return entity, nil
}
Beispiel #28
0
func initPgp(kr string, keyids []string) {
	f, err := os.Open(kr)
	if err != nil {
		log.Fatalf("Can't open keyring: %v", err)
	}
	defer f.Close()

	kl, err := openpgp.ReadKeyRing(f)
	if err != nil {
		log.Fatalf("Can't read keyring: %v", err)
	}

	var hprefs, sprefs []uint8

	for _, w := range keyids {
		for _, e := range kl {
			if e.PrimaryKey.KeyIdShortString() == w {
				pi := primaryIdentity(e)
				ss := pi.SelfSignature

				hprefs = intersectPreferences(hprefs, ss.PreferredHash)
				sprefs = intersectPreferences(sprefs, ss.PreferredSymmetric)
				encryptKeys = append(encryptKeys, e)
			}
		}
	}

	if len(encryptKeys) != len(keyids) {
		log.Fatalf("Couldn't find all keys")
	}
	if len(hprefs) == 0 {
		log.Fatalf("No common hashes for encryption keys")
	}
	if len(sprefs) == 0 {
		log.Fatalf("No common symmetric ciphers for encryption keys")
	}
}
Beispiel #29
0
// LoadKeyRing reads the unarmoured keyring stored at the named path.
func LoadKeyRing(path string) (keyRing *KeyRing, err error) {
	file, err := os.Open(path)
	if err != nil {
		return
	}
	defer file.Close()

	el, err := openpgp.ReadKeyRing(file)
	if err != nil {
		return
	}

	keyRing = new(KeyRing)
	keyRing.path = path
	keyRing.Entities = map[string]*openpgp.Entity{}
	for _, e := range el {
		if e.PrivateKey != nil {
			keyRing.private = true
		}
		id := fmt.Sprintf("%x", e.PrimaryKey.Fingerprint)
		keyRing.Entities[id] = e
	}
	return
}
func loadKeys() {
	secring := filepath.Join(keysDir, "image-signing", "secring.gpg")
	s, err := os.Open(secring)
	if err != nil {
		log.Fatalf("No secret keyring found in %s\n", keysDir)
	}
	defer s.Close()

	el, err := openpgp.ReadKeyRing(s)
	if err != nil {
		log.Fatal("Could not read secret keyring, will not sign tarballs:", err)
	}

	for _, e := range el {
		for i := range e.Identities {
			log.Printf("Signing key: \"%s\"\n", i)
			signingKey = e
			return
		}
	}
	if signingKey == nil {
		log.Fatal("Could not find a signing identity in the keyring")
	}
}