Exemplo n.º 1
0
// Import imports an armoured public key block.
func (keyRing *KeyRing) Import(armoured string) (n int, err error) {
	buf := bytes.NewBufferString(armoured)
	el, err := openpgp.ReadArmoredKeyRing(buf)
	if err != nil {
		return
	}

	for _, e := range el {
		if keyRing.private && e.PrivateKey == nil {
			err = ErrSecRing
			return
		} else if !keyRing.private && e.PrivateKey != nil {
			err = ErrPubRing
			return
		}

		for name, id := range e.Identities {
			err = e.PrimaryKey.VerifyUserIdSignature(name, id.SelfSignature)
			if err != nil {
				return
			}
		}
	}

	for _, e := range el {
		id := fmt.Sprintf("%x", e.PrimaryKey.Fingerprint)
		if _, ok := keyRing.Entities[id]; !ok {
			keyRing.Entities[id] = e
			n++
		}
	}
	return
}
Exemplo n.º 2
0
// Encode encodes data to a base64 encoded using the secconf codec.
// data is encrypted with all public keys found in the supplied keyring.
func Encode(data []byte, keyring io.Reader) ([]byte, error) {
	entityList, err := openpgp.ReadArmoredKeyRing(keyring)
	if err != nil {
		return nil, err
	}
	buffer := new(bytes.Buffer)
	encoder := base64.NewEncoder(base64.StdEncoding, buffer)
	pgpWriter, err := openpgp.Encrypt(encoder, entityList, nil, nil, nil)
	if err != nil {
		return nil, err
	}
	gzWriter := gzip.NewWriter(pgpWriter)
	if _, err := gzWriter.Write(data); err != nil {
		return nil, err
	}
	if err := gzWriter.Close(); err != nil {
		return nil, err
	}
	if err := pgpWriter.Close(); err != nil {
		return nil, err
	}
	if err := encoder.Close(); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}
Exemplo n.º 3
0
func TestParse(t *testing.T) {
	b, rest := Decode(clearsignInput)
	if b == nil {
		t.Fatal("failed to decode clearsign message")
	}
	if !bytes.Equal(rest, []byte("trailing")) {
		t.Errorf("unexpected remaining bytes returned: %s", string(rest))
	}
	if b.ArmoredSignature.Type != "PGP SIGNATURE" {
		t.Errorf("bad armor type, got:%s, want:PGP SIGNATURE", b.ArmoredSignature.Type)
	}
	expected := []byte("Hello world\r\nline 2")
	if !bytes.Equal(b.Bytes, expected) {
		t.Errorf("bad body, got:%x want:%x", b.Bytes, expected)
	}

	expected = []byte("Hello world\nline 2\n")
	if !bytes.Equal(b.Plaintext, expected) {
		t.Errorf("bad plaintext, got:%x want:%x", b.Plaintext, expected)
	}

	keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(signingKey))
	if err != nil {
		t.Errorf("failed to parse public key: %s", err)
	}

	if _, err := openpgp.CheckDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body); err != nil {
		t.Errorf("failed to check signature: %s", err)
	}
}
Exemplo n.º 4
0
Arquivo: pgp.go Projeto: Novemburr/mig
// ArmoredKeysToKeyring takes a list of PGP keys in armored form and transforms
// it into a keyring that can be used in other openpgp's functions
func ArmoredKeysToKeyring(keys [][]byte) (keyring io.ReadSeeker, keycount int, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("ArmoredPubKeysToKeyRing() -> %v", e)
		}
	}()
	var buf bytes.Buffer
	// iterate over the keys, and load them into an io.Reader keyring
	for i, key := range keys {
		// Load PGP public key
		el, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(key))
		if err != nil {
			panic(fmt.Errorf("key num.%d failed to load with error %v", i, err))
		}
		keycount += 1
		if len(el) != 1 {
			err = fmt.Errorf("PGP key contains %d entities, wanted 1", len(el))
			panic(err)
		}
		// serialize entities into io.Reader
		if el[0].PrivateKey != nil {
			err = el[0].SerializePrivate(&buf, nil)
		} else {
			err = el[0].Serialize(&buf)
		}
		if err != nil {
			panic(err)
		}
	}
	keyring = bytes.NewReader(buf.Bytes())
	return
}
Exemplo n.º 5
0
Arquivo: pgp.go Projeto: Novemburr/mig
// KeyringToArmoredPubKeys reads all public keys from a keyring and returned their armored format
// into map of keys indexed by key fingerprint
func KeyringToArmoredPubKeys(keyring io.ReadCloser) (armoredkeys map[string][]byte, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("KeyringToArmoredPubKeys() -> %v", e)
		}
	}()
	els, err := openpgp.ReadArmoredKeyRing(keyring)
	if err != nil {
		panic(err)
	}
	for _, el := range els {
		fingerprint := hex.EncodeToString(el.PrimaryKey.Fingerprint[:])
		var pubkeybuf bytes.Buffer
		err = el.Serialize(&pubkeybuf)
		if err != nil {
			panic(err)
		}
		armoredbuf := bytes.NewBuffer(nil)
		ewrbuf, err := armor.Encode(armoredbuf, openpgp.PublicKeyType, nil)
		if err != nil {
			panic(err)
		}
		_, err = ewrbuf.Write(pubkeybuf.Bytes())
		if err != nil {
			panic(err)
		}
		ewrbuf.Close()
		armoredkeys[fingerprint] = armoredbuf.Bytes()
	}
	return
}
Exemplo n.º 6
0
Arquivo: pgp.go Projeto: Novemburr/mig
func ArmorPubKey(pubkey []byte) (armoredPubKey []byte, err error) {
	var pubkeybuf bytes.Buffer
	// Load PGP public key
	el, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(pubkey))
	if err != nil {
		panic(err)
	}
	// serialize entities into io.Reader
	err = el[0].Serialize(&pubkeybuf)
	if err != nil {
		panic(err)
	}
	armoredbuf := bytes.NewBuffer(nil)
	ewrbuf, err := armor.Encode(armoredbuf, openpgp.PublicKeyType, nil)
	if err != nil {
		panic(err)
	}
	_, err = ewrbuf.Write(pubkeybuf.Bytes())
	if err != nil {
		panic(err)
	}
	ewrbuf.Close()
	armoredPubKey = armoredbuf.Bytes()
	return
}
Exemplo n.º 7
0
//GetPri gets packet.PrivateKEy and openpgp.Entity of Decrypted Private Key from ascii armor
func GetPri(asciiPri string, pripwd string) (priKey packet.PrivateKey, priEnt openpgp.Entity, err error) {
	read1 := bytes.NewReader([]byte(asciiPri))
	entityList, errReadArm := openpgp.ReadArmoredKeyRing(read1)
	if errReadArm != nil {
		//		fmt.Println("Reading PriKey ", errReadArm.Error())
		err = errReadArm
		return
	}
	for _, can_pri := range entityList {
		smPr := can_pri.PrivateKey
		retEntity := can_pri
		if smPr == nil {
			//			fmt.Println("No Private Key")
			err = errors.New("No private key found in armor")
			return
		}

		priKey = *smPr

		errDecr := priKey.Decrypt([]byte(pripwd))
		if errDecr != nil {
			//			fmt.Println("Decrypting ", errDecr.Error())
			err = errDecr
			return
		}
		retEntity.PrivateKey = &priKey
		priEnt = *retEntity
	}

	return
}
Exemplo n.º 8
0
// TransformArmoredPubKeysToKeyring takes a list of public PGP key in armored form and transforms
// it into a keyring that can be used in other openpgp's functions
func ArmoredPubKeysToKeyring(pubkeys []string) (keyring io.Reader, keycount int, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("ArmoredePubKeysToKeyRing() -> %v", e)
		}
	}()
	var buf bytes.Buffer
	// iterate over the keys, and load them into an io.Reader keyring
	for _, key := range pubkeys {
		// Load PGP public key
		el, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(key))
		if err != nil {
			panic(err)
		}
		keycount += 1
		if len(el) != 1 {
			err = fmt.Errorf("Public GPG Key contains %d entities, wanted 1\n", len(el))
			panic(err)
		}
		// serialize entities into io.Reader
		err = el[0].Serialize(&buf)
		if err != nil {
			panic(err)
		}
	}
	keyring = bytes.NewReader(buf.Bytes())
	return
}
Exemplo n.º 9
0
func newPGPFilter(conf map[string]string) (filter, error) {
	if conf["pubkey"] == "" {
		return nil, errors.New("pubkey required")
	}
	to, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer([]byte(conf["pubkey"])))
	if err != nil {
		return nil, fmt.Errorf("Couldn't read pubkey: %s", err)
	}

	pr, pw := io.Pipe()
	f := &pgpFilter{
		r:     pr,
		pw:    pw,
		ready: make(chan bool),
	}
	go func() {
		w, err := openpgp.Encrypt(pw, to, nil, nil, nil) // Not signing yet, sorry
		f.pgpw = w
		f.ready <- true
		if err != nil {
			pr.CloseWithError(err)
			pw.CloseWithError(err)
			return
		}
		log.Print("enc returned")
	}()
	return f, nil
}
Exemplo n.º 10
0
func toEntity(k string) *openpgp.Entity {
	es, err := openpgp.ReadArmoredKeyRing(strings.NewReader(k))
	if err != nil {
		logger.Panicf("Error reading key: %v", err)
	} else if len(es) != 1 {
		logger.Panicf("Expecting a single entity, got len = %d", len(es))
	}
	return es[0]
}
Exemplo n.º 11
0
func toEntity(k string) *openpgp.Entity {
	es, err := openpgp.ReadArmoredKeyRing(strings.NewReader(k))
	if err != nil {
		log.Fatal("Error reading key", err)
	} else if len(es) != 1 {
		log.Fatal("Expecting a single entity, len = ", len(es))
	}
	return es[0]
}
Exemplo n.º 12
0
func newUnpgpFilter(conf map[string]string) (filter, error) {
	if conf["privatkey"] == "" {
		return nil, errors.New("privatkey required")
	}
	keyRing, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer([]byte(conf["privatkey"])))
	if err != nil {
		return nil, fmt.Errorf("Couldn't read privatkey: %s", err)
	}

	return &unpgpFilter{
		keyRing: keyRing,
		ready:   make(chan bool),
	}, nil
}
Exemplo n.º 13
0
func processArmoredKeyRingFile(keyringFile *string) (entity *openpgp.Entity, entitylist openpgp.EntityList) {
	keyringFileBuffer, err := os.Open(*keyringFile)
	if err != nil {
		log.Fatalln("ERROR: Unable to read keyring file")
	}
	entitylist, err = openpgp.ReadArmoredKeyRing(keyringFileBuffer)
	if err != nil {
		log.Fatal(err)
	}
	entity = entitylist[0]
	debug.Printf("Public key from ASCII armored string:", entity.Identities)

	return entity, entitylist
}
Exemplo n.º 14
0
func VerifySignature(pubKey, signed, signatureArmor string) bool {
	keyRing, err := openpgp.ReadArmoredKeyRing(strings.NewReader(pubKey))
	if err != nil {
		panic(err)
	}
	signer, err := openpgp.CheckArmoredDetachedSignature(
		keyRing,
		strings.NewReader(signed),
		strings.NewReader(signatureArmor),
	)
	if err != nil {
		panic(err)
	}
	return signer != nil
}
Exemplo n.º 15
0
//GetPub gets packet.PublicKey and openpgp.Entity of Public Key from ascii armor
func GetPub(asciiPub string) (pubKey packet.PublicKey, retEntity openpgp.Entity, err error) {
	read1 := bytes.NewReader([]byte(asciiPub))
	entityList, errReadArm := openpgp.ReadArmoredKeyRing(read1)

	if errReadArm != nil {
		err = errReadArm
		return
	}
	for _, pubKeyEntity := range entityList {
		if pubKeyEntity.PrimaryKey != nil {
			pubKey = *pubKeyEntity.PrimaryKey
			retEntity = *pubKeyEntity
		}
	}
	return
}
Exemplo n.º 16
0
Arquivo: pgp.go Projeto: Novemburr/mig
// LoadArmoredPubKey takes a single public key as a byte slice, validates it, and returns its
// its fingerprint or an error
func LoadArmoredPubKey(pubkey []byte) (pgpfingerprint string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("LoadArmoredPubKey() -> %v", e)
		}
	}()
	el, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(pubkey))
	if err != nil {
		panic(err)
	}
	if len(el) != 1 {
		err = fmt.Errorf("Public GPG Key contains %d entities, wanted 1", len(el))
		panic(err)
	}
	entity := el[0]
	fp := hex.EncodeToString(entity.PrimaryKey.Fingerprint[:])
	pgpfingerprint = strings.ToUpper(fp)
	return
}
Exemplo n.º 17
0
func TestSigning(t *testing.T) {
	keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(signingKey))
	if err != nil {
		t.Errorf("failed to parse public key: %s", err)
	}

	for i, test := range signingTests {
		var buf bytes.Buffer

		plaintext, err := Encode(&buf, keyring[0].PrivateKey, nil)
		if err != nil {
			t.Errorf("#%d: error from Encode: %s", i, err)
			continue
		}
		if _, err := plaintext.Write([]byte(test.in)); err != nil {
			t.Errorf("#%d: error from Write: %s", i, err)
			continue
		}
		if err := plaintext.Close(); err != nil {
			t.Fatalf("#%d: error from Close: %s", i, err)
			continue
		}

		b, _ := Decode(buf.Bytes())
		if b == nil {
			t.Errorf("#%d: failed to decode clearsign message", i)
			continue
		}
		if !bytes.Equal(b.Bytes, []byte(test.signed)) {
			t.Errorf("#%d: bad result, got:%x, want:%x", i, b.Bytes, test.signed)
			continue
		}
		if !bytes.Equal(b.Plaintext, []byte(test.plaintext)) {
			t.Errorf("#%d: bad result, got:%x, want:%x", i, b.Plaintext, test.plaintext)
			continue
		}

		if _, err := openpgp.CheckDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body); err != nil {
			t.Errorf("#%d: failed to check signature: %s", i, err)
		}
	}
}
Exemplo n.º 18
0
// DecodeCheckSignature parses the inline signed PGP text, checks the signature,
// and returns plain text if the signature matches.
func DecodeCheckSignature(r io.Reader, armoredPublicKey string) ([]byte, error) {
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	b, _ := clearsign.Decode(data)
	if b == nil {
		return nil, &NotPGPSignedError{}
	}
	keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPublicKey))
	if err != nil {
		return nil, fmt.Errorf("failed to parse public key: %v", err)
	}

	_, err = openpgp.CheckDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body)
	if err != nil {
		return nil, err
	}
	return b.Plaintext, nil
}
Exemplo n.º 19
0
// Deocde decodes data using the secconf codec.
func Decode(data []byte, secertKeyring io.Reader) ([]byte, error) {
	decoder := base64.NewDecoder(base64.StdEncoding, bytes.NewBuffer(data))
	entityList, err := openpgp.ReadArmoredKeyRing(secertKeyring)
	if err != nil {
		return nil, err
	}
	md, err := openpgp.ReadMessage(decoder, entityList, nil, nil)
	if err != nil {
		return nil, err
	}
	gzReader, err := gzip.NewReader(md.UnverifiedBody)
	if err != nil {
		return nil, err
	}
	defer gzReader.Close()
	bytes, err := ioutil.ReadAll(gzReader)
	if err != nil {
		return nil, err
	}
	return bytes, nil
}
Exemplo n.º 20
0
// Encode signs the data returned by the reader and returns an inline signed copy.
func Encode(r io.Reader, armoredPrivateKey, passphrase string) ([]byte, error) {
	keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey))
	if err != nil {
		return nil, err
	}

	privateKey := keyring[0].PrivateKey
	if privateKey.Encrypted {
		err = privateKey.Decrypt([]byte(passphrase))
		if err != nil {
			return nil, err
		}
	}

	var buf bytes.Buffer
	plaintext, err := clearsign.Encode(&buf, privateKey, nil)
	if err != nil {
		return nil, err
	}
	metadata, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	dataToSign := metadata
	if dataToSign[0] == '\n' {
		dataToSign = dataToSign[1:]
	}
	_, err = plaintext.Write([]byte(dataToSign))
	if err != nil {
		return nil, err
	}
	err = plaintext.Close()
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}