Example #1
0
func ReadJSKey() {
	pubringFile, _ := os.Open("path to public keyring")
	defer pubringFile.Close()
	pubring, _ := openpgp.ReadArmoredKeyRing(pubringFile)
	theirPublicKey := getKeyByEmail(pubring, "*****@*****.**")

	secringFile, _ := os.Open("path to private keyring")
	defer secringFile.Close()
	secring, _ := openpgp.ReadArmoredKeyRing(secringFile)
	myPrivateKey := getKeyByEmail(secring, "*****@*****.**")

	myPrivateKey.PrivateKey.Decrypt([]byte("passphrase"))

	var hint openpgp.FileHints
	hint.IsBinary = false
	hint.FileName = "_CONSOLE"
	hint.ModTime = time.Now()

	w, _ := armor.Encode(os.Stdout, "PGP MESSAGE", nil)
	defer w.Close()
	plaintext, _ := openpgp.Encrypt(w, []*openpgp.Entity{theirPublicKey}, myPrivateKey, &hint, nil)
	defer plaintext.Close()

	fmt.Fprintf(plaintext, "黄勇刚在熟悉OpenPGP代码\n")
}
Example #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
}
Example #3
0
// Encode - this function wraps around an Encoder object to decode the passed in data.
// @param io.Reader[] src - This parameter will be used to read the unencrypted data
// @param io.Writer[] dest - This parameter will be used to write the encrypted data
func (e *Encoder) Encode(r io.Reader, w io.Writer) error {
	entitylist, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(e.Key))
	if err != nil {
		return err
	}

	// Encrypt message using public key
	buf := new(bytes.Buffer)
	encrypter, err := openpgp.Encrypt(buf, entitylist, nil, nil, nil)
	if err != nil {
		return err
	}

	_, err = io.Copy(encrypter, r)
	if err != nil {
		return err
	}

	err = encrypter.Close()
	if err != nil {
		return err
	}

	_, err = io.Copy(w, buf)
	return err
}
Example #4
0
func SignersFromKeyring(keyring string) ([]byte, error) {
	var (
		connectionSet = make(map[string]set)
		keyIDToName   = make(map[string]string)
	)

	ring, err := openpgp.ReadArmoredKeyRing(strings.NewReader(keyring))
	if err != nil {
		return nil, err
	}

	for _, entity := range ring {
		for _, ident := range entity.Identities {
			keyID := entity.PrimaryKey.KeyIdString()
			name := ident.UserId.Name
			keyIDToName[keyID] = ident.Name
			connectionSet[name] = set{}
			for _, sig := range ident.Signatures {
				if keys := ring.KeysById(*sig.IssuerKeyId); len(keys) > 0 {
					for _, key := range keys {
						connectionSet[name].Add(key.PublicKey.KeyIdString())
					}
				}
			}
		}
	}

	return newSigned(connectionSet, keyIDToName).html(), nil
}
Example #5
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, e.PrimaryKey, 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
}
Example #6
0
// ClearSign the assertions using the private key and return a clear-signed buffer.
// If the private key is encrypted, the passphrase must be supplied to decrypt
// the key.
func ClearSign(assertions, armoredPrivateKey, passphrase string) ([]byte, error) {
	keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey))
	if err != nil {
		return nil, err
	}

	// Decrypt the private key, if it is encrypted
	privateKey := keyring[0].PrivateKey
	if privateKey.Encrypted {
		err = privateKey.Decrypt([]byte(passphrase))
		if err != nil {
			return nil, err
		}
	}

	// Sign the assertions and save the result in the buffer
	var buf bytes.Buffer
	plaintext, err := clearsign.Encode(&buf, privateKey, nil)
	if err != nil {
		return nil, err
	}
	_, err = plaintext.Write([]byte(assertions))
	if err != nil {
		return nil, err
	}
	err = plaintext.Close()
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Example #7
0
func LoadKeyring(path string) (openpgp.EntityList, error) {
	if path == "" {
		return nil, util.Errorf("no keyring configured")
	}
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	// Accept both ASCII-armored and binary encodings
	keyring, err := openpgp.ReadArmoredKeyRing(f)
	if err != nil && err.Error() == "openpgp: invalid argument: no armored data found" {
		offset, seekErr := f.Seek(0, os.SEEK_SET)
		if offset != 0 || seekErr != nil {
			return nil, util.Errorf(
				"couldn't seek to beginning, got %d %s",
				offset,
				seekErr,
			)
		}
		keyring, err = openpgp.ReadKeyRing(f)
	}

	return keyring, err
}
Example #8
0
// Parse a single ASCII armored PGP pubkey file and add it to the repo.
func ParseArmorFile(keyPath string) {
	ascii, err := ioutil.ReadFile(keyPath)
	if err != nil {
		panic(err)
	}

	asciiReader := bytes.NewReader([]byte(ascii))

	// An armored key ring can contain one or more ascii key blobs.
	entityList, errReadArm := openpgp.ReadArmoredKeyRing(asciiReader)
	if errReadArm != nil {
		log.Println("Reading Pubkey ", errReadArm.Error())
		return
	}

	for _, pubKeyEntity := range entityList {
		if pubKeyEntity.PrimaryKey != nil {
			pubKey := *pubKeyEntity.PrimaryKey
			fingerprint := hex.EncodeToString(pubKey.Fingerprint[:])

			GetRepo().Add(newRepoEntry(
				strings.ToUpper(fingerprint),
				pubKey.CreationTime.String(),
				"0x"+pubKey.KeyIdString(),
				"email",
				"",
				string(ascii[:]),
			))
		}
	}
	return
}
Example #9
0
func Decrypt(data string, key_file string) (string, error) {

	secretKeyring, err := os.Open(key_file)
	if err != nil {
		return nil, err
	}
	defer secretKeyring.Close()

	// Taken from crypt and adapted
	decoder := base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(data))
	entityList, err := openpgp.ReadArmoredKeyRing(secretKeyring)
	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 string(bytes), nil
}
Example #10
0
// Decode - this function wraps around a Decoder object to decode the passed in data.
// @param io.Reader[] src - This parameter will be used to read the encrypted data
// @param io.Writer[] dest - This parameter will be used to write the unencrypted data
func (d *Decoder) Decode(r io.Reader, w io.Writer) error {
	entitylist, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(d.Key))
	if err != nil {
		return err
	}
	entity := entitylist[0]

	if entity.PrivateKey != nil && entity.PrivateKey.Encrypted {
		if len(d.Passphrase) == 0 {
			return errors.New("Private key is encrypted but you did not provide a passphrase")
		}
		err := entity.PrivateKey.Decrypt(d.Passphrase)
		if err != nil {
			return errors.New("Failed to decrypt private key. Did you use the wrong passphrase? (" + err.Error() + ")")
		}
	}
	for _, subkey := range entity.Subkeys {
		if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted {
			err := subkey.PrivateKey.Decrypt(d.Passphrase)
			if err != nil {
				return errors.New("Failed to decrypt subkey. Did you use the wrong passphrase? (" + err.Error() + ")")
			}
		}
	}

	read, err := openpgp.ReadMessage(r, entitylist, nil, nil)
	if err != nil {
		return err
	}

	_, err = io.Copy(w, read.LiteralData.Body)
	return err

}
Example #11
0
File: pgp.go Project: igofman/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
}
Example #12
0
func testParse(t *testing.T, input []byte, expected, expectedPlaintext string) {
	b, rest := Decode(input)
	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)
	}
	if !bytes.Equal(b.Bytes, []byte(expected)) {
		t.Errorf("bad body, got:%x want:%x", b.Bytes, expected)
	}

	if !bytes.Equal(b.Plaintext, []byte(expectedPlaintext)) {
		t.Errorf("bad plaintext, got:%x want:%x", b.Plaintext, expectedPlaintext)
	}

	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)
	}
}
Example #13
0
File: pgp.go Project: igofman/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
}
Example #14
0
File: pgp.go Project: igofman/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
}
Example #15
0
func (kr *Keyring) loadFile(path string) error {
	trustedKey, err := os.Open(path)
	if err != nil {
		return err
	}
	defer trustedKey.Close()
	entityList, err := openpgp.ReadArmoredKeyRing(trustedKey)
	if err != nil {
		return err
	}
	if len(entityList) < 1 {
		return errors.New("missing opengpg entity")
	}
	fingerprint := fingerprintToFilename(entityList[0].PrimaryKey.Fingerprint)
	keyFile := filepath.Base(trustedKey.Name())
	if fingerprint != keyFile {
		return errors.Errorf("fingerprint mismatch: %q:%q", keyFile, fingerprint)
	}

	prefix, err := pathToACIdentifier(path)
	if err != nil {
		return err
	}

	kr.EntityList = append(kr.EntityList, entityList[0])
	kr.paths = append(kr.paths, path)
	kr.prefixes = append(kr.prefixes, prefix)

	return nil
}
Example #16
0
func getAccountPublicKey(account *models.Account) (*openpgp.Entity, error) {
	if account.PublicKey != "" {
		cursor, err := gorethink.Db(cfg.RethinkDatabase).Table("keys").Get(account.PublicKey).Run(session)
		if err != nil {
			return nil, err
		}
		defer cursor.Close()

		var key *models.Key
		if err := cursor.One(&key); err != nil {
			return nil, err
		}

		keyring, err := openpgp.ReadArmoredKeyRing(strings.NewReader(key.Key))
		if err != nil {
			return nil, err
		}

		return keyring[0], nil
	}

	cursor, err := gorethink.Db(cfg.RethinkDatabase).Table("keys").GetAllByIndex("owner", account.ID).Run(session)
	if err != nil {
		return nil, err
	}
	defer cursor.Close()

	var keys []*models.Key
	if err := cursor.All(&keys); err != nil {
		return nil, err
	}

	if len(keys) == 0 {
		return nil, fmt.Errorf("Recipient has no public key")
	}

	keyring, err := openpgp.ReadArmoredKeyRing(strings.NewReader(keys[0].Key))
	if err != nil {
		return nil, err
	}

	return keyring[0], nil
}
Example #17
0
func (h *testHarness) loadEntities() []*openpgp.Entity {
	if h.Err != nil {
		return nil
	}
	keyring, err := openpgp.ReadArmoredKeyRing(strings.NewReader(testUsers))
	if err != nil {
		h.Err = err
		return nil
	}
	return keyring
}
Example #18
0
func reviewKey(prefix types.ACIdentifier, key *os.File, fingerprint string) (bool, error) {
	defer key.Seek(0, os.SEEK_SET)

	kr, err := openpgp.ReadArmoredKeyRing(key)
	if err != nil {
		return false, errors.Trace(err)
	}

	if prefix == Root {
		fmt.Println("Prefix: ROOT KEY (matches all names)")
	} else {
		fmt.Println("Prefix:", prefix)
	}
	for _, k := range kr {
		fmt.Println(KeyDescription(k))
	}

	if fingerprint == "" {
		// TODO: use UI, check if interactive
		in := bufio.NewReader(os.Stdin)
		for {
			fmt.Printf("Are you sure you want to trust this key (yes/no)? ")
			input, err := in.ReadString('\n')
			if err != nil {
				return false, errors.Errorf("error reading input: %v", err)
			}
			switch input {
			case "yes\n":
				return true, nil
			case "no\n":
				return false, nil
			default:
				fmt.Printf("Please enter 'yes' or 'no'")
			}
		}
	} else if fpBytes, err := hex.DecodeString(
		strings.Map(
			// Strip spaces
			func(r rune) rune {
				if unicode.IsSpace(r) {
					return -1
				}
				return r
			}, fingerprint)); err != nil {
		return false, errors.Trace(err)
	} else if bytes.Compare(fpBytes, kr[0].PrimaryKey.Fingerprint[:]) != 0 {
		fmt.Printf("Fingerprint mismatch (expected %#v)\n", fingerprint)
		return false, nil
	} else {
		return true, nil
	}
	return true, nil
}
Example #19
0
File: aci.go Project: nhlfr/rkt
// NewDetachedSignature creates a new openpgp armored detached signature for the given ACI
// signed with armoredPrivateKey.
func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error) {
	entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey))
	if err != nil {
		return nil, err
	}
	if len(entityList) < 1 {
		return nil, errors.New("empty entity list")
	}
	signature := &bytes.Buffer{}
	if err := openpgp.ArmoredDetachSign(signature, entityList[0], aci, nil); err != nil {
		return nil, err
	}
	return signature, nil
}
Example #20
0
func ApprovalCheck(PolicyFile, SignaturesFile, Id string) (bool, error) {
	var (
		commit     SignedCommit               // Commit corresponding to be verified
		developers openpgp.EntityList         // List of all developers whose public keys are in the policy file
		approvers  map[string]*openpgp.Entity // Map of developers who provided a valid signature. Indexed by public key id (openpgp.PrimaryKey.KeyIdString)
		err        error
	)

	commit.Policy.Threshold, commit.Policy.DevPubKeys, commit.Policy.CothKey, err = PolicyScanner(PolicyFile)
	checkFileError(err, PolicyFile)
	commit.Signatures, err = SigScanner(SignaturesFile)
	checkFileError(err, SignaturesFile)
	commit.CommitID = Id
	// commit.CommitID, err = CommitScanner(CommitIdFile)
	// checkFileError(err, CommitIdFile)
	// commit.Approval = false

	approvers = make(map[string]*openpgp.Entity)

	// Creating openpgp entitylist from list of public keys
	developers = make(openpgp.EntityList, 0)
	for _, pubkey := range commit.Policy.DevPubKeys {
		keybuf, err := openpgp.ReadArmoredKeyRing(strings.NewReader(pubkey))
		if err != nil {
			dbg.Error("Could not decode armored public key", err)
		}
		for _, entity := range keybuf {
			developers = append(developers, entity)
		}
	}

	// Verifying every signature in the list and counting valid ones
	for _, signature := range commit.Signatures {
		result, err := openpgp.CheckArmoredDetachedSignature(developers, bytes.NewBufferString(commit.CommitID), strings.NewReader(signature))
		if err != nil {
			dbg.Lvl1("The signature is invalid or cannot be verified due to", err)
		} else {
			if approvers[result.PrimaryKey.KeyIdString()] == nil { // We need to check that this is a unique signature
				approvers[result.PrimaryKey.KeyIdString()] = result
				dbg.Lvl3("Approver: %+v", result.Identities)
			}
		}
	}

	dbg.Lvl3("Is release approved? ", len(approvers) >= commit.Policy.Threshold)
	// commit.Approval = (len(approvers) >= commit.Policy.Threshold)

	return len(approvers) >= commit.Policy.Threshold, err
	// return commit, err
}
Example #21
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
}
Example #22
0
func (c *config) loadPGPKey(pathToKey string) (ent *openpgp.Entity, err error) {
	var keyRC io.ReadCloser
	if strings.Index(pathToKey, "http") == 0 {
		var httpData *http.Response
		httpData, err = c.httpClient.Get(pathToKey)
		if httpData != nil {
			keyRC = httpData.Body
			defer func() {
				if err2 := keyRC.Close(); err2 != nil {
					c.maillog.Errorf("keyRC.Close(): %s", err2)
				}
			}()
		}
		if err != nil {
			return nil, fmt.Errorf("Loading of remote public key from URL %q failed:\n%s", pathToKey, err)
		}
		if httpData.StatusCode != 200 {
			return nil, fmt.Errorf("Loading remote public key failed from URL %q. StatusCode have %d StatusCode want %d", pathToKey, httpData.StatusCode, 200)
		}

	} else {
		if false == fileExists(pathToKey) {
			return nil, fmt.Errorf("File %q not found", pathToKey)
		}
		var f *os.File
		f, err = os.Open(pathToKey)
		if err != nil {
			return nil, fmt.Errorf("File %q not loaded because of error: %s", pathToKey, err)
		}
		keyRC = f
		defer func() {
			if err2 := keyRC.Close(); err2 != nil {
				c.maillog.Errorf("keyRC.Close(): %s", err2)
			}
		}()
	}

	keyList, err := openpgp.ReadArmoredKeyRing(keyRC)
	if err != nil {
		return nil, fmt.Errorf("Cannot read public key %q: %s", pathToKey, err)
	}
	ent = keyList[0]

	if ent.PrivateKey != nil {
		ent = nil
		err = fmt.Errorf("PrivateKey found. Not allowed. Please remove it from resouce: %q", pathToKey)
	}
	return
}
Example #23
0
func Sign(plaintext string) string {
	secringFile, _ := os.Open("C:/Users/huangyg/Desktop/huangyg.sec")
	defer secringFile.Close()
	secring, _ := openpgp.ReadArmoredKeyRing(secringFile)
	myPrivateKey := getKeyByEmail(secring, "*****@*****.**")

	myPrivateKey.PrivateKey.Decrypt([]byte("passphrase"))

	ret := ""
	buf := bytes.NewBufferString(ret)
	openpgp.ArmoredDetachSignText(buf, myPrivateKey, bytes.NewBufferString(plaintext), nil)
	ret = buf.String()

	return ret
}
Example #24
0
// NewMessageAndSignature generates a new random message signed by the given entity.
// NewMessageAndSignature returns message, signature and an error if any.
func NewMessageAndSignature(armoredPrivateKey string) (io.ReadSeeker, io.ReadSeeker, error) {
	entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey))
	if err != nil {
		return nil, nil, err
	}
	if len(entityList) < 1 {
		return nil, nil, errors.New("empty entity list")
	}
	signature := &bytes.Buffer{}
	message := []byte("data")
	if err := openpgp.ArmoredDetachSign(signature, entityList[0], bytes.NewReader(message), nil); err != nil {
		return nil, nil, err
	}
	return bytes.NewReader(message), bytes.NewReader(signature.Bytes()), nil
}
Example #25
0
File: smtp.go Project: bfix/gospel
// EncryptMailMessage encrypts a mail with given public key.
func EncryptMailMessage(key, body []byte) ([]byte, error) {
	rdr := bytes.NewBuffer(key)
	keyring, err := openpgp.ReadArmoredKeyRing(rdr)
	if err != nil {
		logger.Println(logger.ERROR, err.Error())
		return nil, err
	}

	out := new(bytes.Buffer)
	ct, err := armor.Encode(out, "PGP MESSAGE", nil)
	if err != nil {
		logger.Println(logger.ERROR, "Can't create armorer: "+err.Error())
		return nil, err
	}
	wrt, err := openpgp.Encrypt(ct, []*openpgp.Entity{keyring[0]}, nil, &openpgp.FileHints{IsBinary: true}, nil)
	if err != nil {
		logger.Println(logger.ERROR, err.Error())
		return nil, err
	}
	wrt.Write(body)
	wrt.Close()
	ct.Close()

	tmp := make([]byte, 30)
	_, err = io.ReadFull(rand.Reader, tmp)
	if err != nil {
		logger.Println(logger.ERROR, err.Error())
		return nil, err
	}
	bndry := fmt.Sprintf("%x", tmp)
	msg := new(bytes.Buffer)
	msg.WriteString(
		"MIME-Version: 1.0\n" +
			"Content-Type: multipart/encrypted;\n" +
			" protocol=\"application/pgp-encrypted\";\n" +
			" boundary=\"" + bndry + "\"\n\n" +
			"This is an OpenPGP/MIME encrypted message (RFC 4880 and 3156)\n" +
			"--" + bndry + "\n" +
			"Content-Type: application/pgp-encrypted\n" +
			"Content-Description: PGP/MIME version identification\n\n" +
			"Version: 1\n\n" +
			"--" + bndry + "\n" +
			"Content-Type: application/octet-stream;\n name=\"encrypted.asc\"\n" +
			"Content-Description: OpenPGP encrypted message\n" +
			"Content-Disposition: inline;\n filename=\"encrypted.asc\"\n\n" +
			string(out.Bytes()) + "\n--" + bndry + "--")
	return msg.Bytes(), nil
}
Example #26
0
func (ks *Keystore) TrustedKeyPrefixExists(prefix string, r io.ReadSeeker) (bool, error) {
	defer r.Seek(0, os.SEEK_SET)

	entityList, err := openpgp.ReadArmoredKeyRing(r)
	if err != nil {
		return false, err
	}
	if len(entityList) < 1 {
		return false, errors.New("missing opengpg entity")
	}
	pubKey := entityList[0].PrimaryKey
	fileName := fingerprintToFilename(pubKey.Fingerprint)

	pathNamesRoot := []string{
		// example: /etc/rkt/trustedkeys/root.d/8b86de38890ddb7291867b025210bd8888182190
		path.Join(ks.LocalRootPath, fileName),
		// example: /usr/lib/rkt/trustedkeys/root.d/8b86de38890ddb7291867b025210bd8888182190
		path.Join(ks.SystemRootPath, fileName),
	}

	var pathNamesPrefix []string
	if prefix != "" {
		acidentifier, err := types.NewACIdentifier(prefix)
		if err != nil {
			return false, err
		}
		pathNamesPrefix = []string{
			// example: /etc/rkt/trustedkeys/prefix.d/coreos.com/etcd/8b86de38890ddb7291867b025210bd8888182190
			path.Join(ks.LocalPrefixPath, acidentifier.String(), fileName),
			// example: /usr/lib/rkt/trustedkeys/prefix.d/coreos.com/etcd/8b86de38890ddb7291867b025210bd8888182190
			path.Join(ks.SystemPrefixPath, acidentifier.String(), fileName),
		}
	}

	pathNames := append(pathNamesRoot, pathNamesPrefix...)
	for _, p := range pathNames {
		_, err := os.Stat(p)
		if err == nil {
			return true, nil
		} else if !os.IsNotExist(err) {
			return false, errwrap.Wrap(fmt.Errorf("cannot check file %q", p), err)
		}
	}

	return false, nil
}
Example #27
0
func encrypt(input string, email string, gConfig map[string]string) string {

	os.MkdirAll(gConfig["PGP_KEY_FOLDER"], 0777)
	keyfileName := path.Join(gConfig["PGP_KEY_FOLDER"], email+".asc")
	keyfileExists, _ := exists(keyfileName)
	if !keyfileExists {

		key := publickey.GetKeyFromEmail(email, gConfig["PGP_KEYSERVER"], gConfig["PGP_KEYSERVER_QUERY"])
		if key == "no keys found" {
			return key + " on keyserver " + gConfig["PGP_KEYSERVER"] + " from query " + gConfig["PGP_KEYSERVER"] + gConfig["PGP_KEYSERVER_QUERY"] + email
		}

		if key == "invalid host" {
			return gConfig["PGP_KEYSERVER"] + " is offline and your key has not previously been cached."
		}

		f, err := os.Create(keyfileName)
		if err != nil {
			fmt.Println(err)
		}
		n, err := io.WriteString(f, key)
		if err != nil {
			fmt.Println(n, err)
		}
		f.Close()
	}

	to, err := os.Open(keyfileName)
	logging.CheckFatal(err)

	defer to.Close()

	entitylist, err := openpgp.ReadArmoredKeyRing(to)

	buf := new(bytes.Buffer)
	w, _ := armor.Encode(buf, encryptionType, nil)
	plaintext, _ := openpgp.Encrypt(w, entitylist, nil, nil, nil)

	fmt.Fprintf(plaintext, input)
	plaintext.Close()
	w.Close()

	return buf.String()

}
Example #28
0
func encodeCloudYAML(c *gc.C, yaml string) string {
	// TODO(wallyworld) - move test signing key elsewhere
	keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(sstesting.SignedMetadataPrivateKey))
	c.Assert(err, jc.ErrorIsNil)
	privateKey := keyring[0].PrivateKey
	err = privateKey.Decrypt([]byte(sstesting.PrivateKeyPassphrase))
	c.Assert(err, jc.ErrorIsNil)

	var buf bytes.Buffer
	plaintext, err := clearsign.Encode(&buf, privateKey, nil)
	c.Assert(err, jc.ErrorIsNil)

	_, err = plaintext.Write([]byte(yaml))
	c.Assert(err, jc.ErrorIsNil)
	err = plaintext.Close()
	c.Assert(err, jc.ErrorIsNil)
	return string(buf.Bytes())
}
Example #29
0
File: pgp.go Project: igofman/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
}
Example #30
0
func encrypt(input string, email string) string {

	to, err := os.Open(email + ".asc")
	logging.CheckFatal(err)
	defer to.Close()

	entitylist, err := openpgp.ReadArmoredKeyRing(to)

	buf := new(bytes.Buffer)
	w, _ := armor.Encode(buf, encryptionType, nil)
	plaintext, _ := openpgp.Encrypt(w, entitylist, nil, nil, nil)

	fmt.Fprintf(plaintext, input)
	plaintext.Close()
	w.Close()

	return buf.String()

}