Exemplo n.º 1
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
}
Exemplo n.º 2
0
// NewPGPEncryptor returns a new PGPEncryptor instance, prepared for encrypting one single
// mail with the given parameters.
func NewPGPEncryptor(signingKey, encryptionKey *openpgp.Entity, keepHeaders []string) (*PGPEncryptor, error) {
	if encryptionKey == nil {
		return nil, errors.New("missing encryption key")
	}
	e := &PGPEncryptor{}
	e.keepHeaders = keepHeaders
	e.pgpBuffer = &bytes.Buffer{}
	e.headerBuffer = NewHeaderBuffer()
	var err error
	e.asciiWriter, err = armor.Encode(e.pgpBuffer, "PGP MESSAGE", nil)
	if err != nil {
		return nil, err
	}
	cfg := &packet.Config{
		DefaultCipher: packet.CipherAES256,
		DefaultHash:   crypto.SHA256,
	}
	e.pgpWriter, err = openpgp.Encrypt(e.asciiWriter,
		[]*openpgp.Entity{encryptionKey}, signingKey,
		&openpgp.FileHints{IsBinary: true}, cfg)
	if err != nil {
		return nil, err
	}
	return e, nil
}
Exemplo n.º 3
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")
}
Exemplo n.º 4
0
func encryptOpenpgp(data io.Reader, recipient string, gpghome string) ([]byte, error) {
	pubkeyfile, err := os.Open(fmt.Sprintf("%s%spubring.gpg", gpghome, string(os.PathSeparator)))
	if err != nil {
		fmt.Println("Failed to open pubring", err)
		return nil, err
	}

	pubring, err := openpgp.ReadKeyRing(pubkeyfile)
	if err != nil {
		fmt.Println("Failed to open pubring", err)
		return nil, err
	}

	pubkey := findKey(pubring, recipient)

	buf := bytes.NewBuffer(nil)
	w, _ := armor.Encode(buf, "PGP MESSAGE", nil)
	plaintext, err := openpgp.Encrypt(w, []*openpgp.Entity{pubkey}, nil, nil, nil)
	if err != nil {
		return nil, err
	}
	//reader := bytes.NewReader(data)
	_, err = io.Copy(plaintext, data)
	plaintext.Close()
	w.Close()
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil

}
Exemplo n.º 5
0
// EncryptShares takes an ordered set of Shamir key share fragments and
// PGP public keys and encrypts each Shamir key fragment with the corresponding
// public key
//
// Note: There is no corresponding test function; this functionality is
// thoroughly tested in the init and rekey command unit tests
func EncryptShares(secretShares [][]byte, pgpKeys []string) ([][]byte, error) {
	if len(secretShares) != len(pgpKeys) {
		return nil, fmt.Errorf("Mismatch between number of generated shares and number of PGP keys")
	}
	encryptedShares := [][]byte{}
	for i, keystring := range pgpKeys {
		data, err := base64.StdEncoding.DecodeString(keystring)
		if err != nil {
			return nil, fmt.Errorf("Error decoding given PGP key: %s", err)
		}
		entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data)))
		if err != nil {
			return nil, fmt.Errorf("Error parsing given PGP key: %s", err)
		}
		ctBuf := bytes.NewBuffer(nil)
		pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil)
		if err != nil {
			return nil, fmt.Errorf("Error setting up encryption for PGP message: %s", err)
		}
		_, err = pt.Write([]byte(hex.EncodeToString(secretShares[i])))
		if err != nil {
			return nil, fmt.Errorf("Error encrypting PGP message: %s", err)
		}
		pt.Close()
		encryptedShares = append(encryptedShares, ctBuf.Bytes())
	}
	return encryptedShares, nil
}
Exemplo n.º 6
0
func WriteEncrypted(ciphertext io.WriteCloser, el openpgp.EntityList) (io.WriteCloser, error) {
	plaintext, err := openpgp.Encrypt(ciphertext, el, nil, nil, nil)
	if err != nil {
		return nil, err
	}
	return &encryptedWriter{ciphertext, plaintext}, nil
}
Exemplo n.º 7
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.º 8
0
// EncryptShares takes an ordered set of byte slices to encrypt and the
// corresponding base64-encoded public keys to encrypt them with, encrypts each
// byte slice with the corresponding public key.
//
// Note: There is no corresponding test function; this functionality is
// thoroughly tested in the init and rekey command unit tests
func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) {
	if len(input) != len(pgpKeys) {
		return nil, nil, fmt.Errorf("Mismatch between number items to encrypt and number of PGP keys")
	}
	encryptedShares := make([][]byte, 0, len(pgpKeys))
	entities, err := GetEntities(pgpKeys)
	if err != nil {
		return nil, nil, err
	}
	for i, entity := range entities {
		ctBuf := bytes.NewBuffer(nil)
		pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil)
		if err != nil {
			return nil, nil, fmt.Errorf("Error setting up encryption for PGP message: %s", err)
		}
		_, err = pt.Write(input[i])
		if err != nil {
			return nil, nil, fmt.Errorf("Error encrypting PGP message: %s", err)
		}
		pt.Close()
		encryptedShares = append(encryptedShares, ctBuf.Bytes())
	}

	fingerprints, err := GetFingerprints(nil, entities)
	if err != nil {
		return nil, nil, err
	}

	return fingerprints, encryptedShares, nil
}
Exemplo n.º 9
0
func encryptAndArmor(input []byte, to []*openpgp.Entity) ([]byte, error) {
	encOutput := &bytes.Buffer{}
	encInput, err := openpgp.Encrypt(encOutput, to, nil, nil, nil)
	if err != nil {
		return nil, err
	}

	if _, err = encInput.Write(input); err != nil {
		return nil, err
	}

	if err = encInput.Close(); err != nil {
		return nil, err
	}

	armOutput := &bytes.Buffer{}
	armInput, err := armor.Encode(armOutput, "PGP MESSAGE", nil)
	if err != nil {
		return nil, err
	}

	if _, err = io.Copy(armInput, encOutput); err != nil {
		return nil, err
	}

	if err = armInput.Close(); err != nil {
		return nil, err
	}

	return armOutput.Bytes(), nil
}
Exemplo n.º 10
0
func (ctx *SecureContext) EncryptRoot() error {
	entityList, err := ctx.ReadAccessList()
	if err != nil {
		return err
	}

	fileCallback := func(filePath string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if fi.IsDir() {
			return nil
		}
		if filepath.Ext(fi.Name()) != ".txt" {
			return nil
		}

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

		filePath = strings.Replace(filePath, ".txt", ".gpg", 1)
		destRootPath := path.Join(ctx.DirectoryRoot, "files")
		destPath := path.Join(destRootPath, filepath.Base(filePath))

		_, err = os.Stat(destRootPath)
		if err != nil {
			err = os.Mkdir(destRootPath, 0700)
			if err != nil {
				return err
			}
		}

		destFp, err := os.Create(destPath)
		if err != nil {
			return err
		}
		defer destFp.Close()

		w, err := armor.Encode(destFp, "PGP MESSAGE", nil)
		if err != nil {
			return err
		}
		defer w.Close()

		cleartext, err := openpgp.Encrypt(w, entityList, nil, nil, nil)
		if err != nil {
			return err
		}
		io.Copy(cleartext, fp)
		cleartext.Close()

		return nil
	}

	return filepath.Walk(ctx.DirectoryRoot, fileCallback)
}
Exemplo n.º 11
0
Arquivo: pgp.go Projeto: lbn/gorwell
func (pgpClient PGPClient) Encrypt(data []byte) []byte {
	// encrypt string
	buf := new(bytes.Buffer)
	w, _ := openpgp.Encrypt(buf, pgpClient.Entities, nil, nil, nil)
	w.Write(data)
	w.Close()

	bytes, _ := ioutil.ReadAll(buf)
	return bytes
}
Exemplo n.º 12
0
Arquivo: gpg.go Projeto: laher/passr
func Encrypt(index int, kring openpgp.EntityList, keyName string, isSigned bool, filename string, message string) error {

	var signed *openpgp.Entity
	if isSigned {
		signed = kring[0]
	}

	//buf := new(bytes.Buffer)
	f, err := os.Create(filename)
	if err != nil {
		logrus.Errorf("#%d: error in Create: %s", index, err)
		return err
	}
	whichKey := openpgp.EntityList{}
	if keyName == "" {
		whichKey = kring[:1]
	} else {
		for _, entity := range kring {
			if entity.PrivateKey != nil {
				pubk := entity.PrivateKey.PublicKey
				logrus.Infof("Key: %s", pubk.KeyIdShortString())
				if pubk.KeyIdShortString() == keyName {
					whichKey = append(whichKey, entity)
				}
			} else {
				if entity.PrimaryKey.KeyIdShortString() == keyName {
					whichKey = append(whichKey, entity)
				}
			}
		}
	}
	w, err := openpgp.Encrypt(f, whichKey, signed, nil /* no hints */, nil)
	if err != nil {
		logrus.Errorf("#%d: error in Encrypt: %s", index, err)
		return err
	}

	_, err = w.Write([]byte(message))
	if err != nil {
		logrus.Errorf("#%d: error writing plaintext: %s", index, err)
		return err
	}
	err = w.Close()
	if err != nil {
		logrus.Errorf("#%d: error closing WriteCloser: %s", index, err)
		return err
	}
	err = f.Close()
	if err != nil {
		logrus.Errorf("#%d: error closing file: %s", index, err)
		return err
	}
	return nil
}
Exemplo n.º 13
0
Arquivo: pgp.go Projeto: lbn/gorwell
func (client PGP) EncryptBytes(secret []byte, target openpgp.EntityList) []byte {
	// encrypt string
	buf := new(bytes.Buffer)
	w, _ := openpgp.Encrypt(buf, target, nil, nil, nil)
	w.Write(secret)
	w.Close()

	bytes, _ := ioutil.ReadAll(buf)
	f, _ := os.Create("./msg.asc")
	f.Write(ToArmor(bytes, PGPMessage))
	defer f.Close()
	return bytes
}
Exemplo n.º 14
0
func main() {
	encrypt_out := flag.String("out", "ciphertext.out", "Ciphertext")

	log.Println("Create key pair")
	// Create a key-pair
	entity, _ := openpgp.NewEntity("The Receiver", "testing",
		"*****@*****.**", nil)

	log.Println("Start encryption")
	config := &packet.Config{
		DefaultHash: crypto.SHA256,
	}
	file, err := os.OpenFile(*encrypt_out, os.O_WRONLY|os.O_CREATE, 0600)

	// For some reason it uses RIPEMD160 ?
	plain, err := openpgp.Encrypt(file, []*openpgp.Entity{entity},
		nil, nil, config)
	if err != nil {
		log.Fatal(err)
	}

	// Input of plaintext: a stream (as we typically would get from a
	// network stream).
	plain.Write([]byte("Hello World plaintext!\n"))
	plain.Close()

	// Decrypt
	read_file, _ := os.Open(*encrypt_out)
	keyring := openpgp.EntityList{entity}

	message, err := openpgp.ReadMessage(read_file, keyring,
		func(keys []openpgp.Key, sym bool) ([]byte, error) {
			log.Printf("Prompt got called\n")
			return nil, nil
		}, nil)
	if err != nil {
		log.Fatal(err)
	}

	// Read the encrypted file and dump plain-text to stdout.
	body_reader := message.UnverifiedBody
	buffer := make([]byte, 1024)
	for {
		n, _ := body_reader.Read(buffer)
		if n == 0 {
			break
		}
		os.Stdout.Write(buffer[0:n])
	}
	log.Println("Done.")
}
Exemplo n.º 15
0
func (bm message) bodyEncrypted(gm *gomail.Message, pgpTo string) {

	pgpBuf := bufpool.Get()
	defer bufpool.Put(pgpBuf)

	msgBuf := bufpool.Get()
	defer bufpool.Put(msgBuf)

	bm.renderTemplate(msgBuf)

	// the next line may crash if the PGP key gets removed ... some how. but the crash is fine
	w, err := openpgp.Encrypt(pgpBuf, openpgp.EntityList{0: bm.mc.pgpEmailKeyEntities[pgpTo]}, nil, nil, nil)
	if err != nil {
		bm.mc.maillog.Errorf("PGP encrypt Error: %s", err)
		return
	}

	_, err = w.Write(msgBuf.Bytes())
	if err != nil {
		bm.mc.maillog.Errorf("PGP encrypt Write Error: %s", err)
		return
	}

	err = w.Close()
	if err != nil {
		bm.mc.maillog.Errorf("PGP encrypt Close Error: %s", err)
		return
	}

	b64Buf := make([]byte, base64.StdEncoding.EncodedLen(pgpBuf.Len()))
	base64.StdEncoding.Encode(b64Buf, pgpBuf.Bytes())

	gm.SetBody("text/plain", "This should be an OpenPGP/MIME encrypted message (RFC 4880 and 3156)")

	gm.Embed(
		bm.mc.pgpAttachmentName,
		gomail.SetCopyFunc(func(w io.Writer) error {
			if _, err := w.Write(pgpStartText); err != nil {
				return err
			}
			if _, err := w.Write(b64Buf); err != nil {
				return err
			}
			if _, err := w.Write(pgpEndText); err != nil {
				return err
			}
			return nil
		}),
	)
}
Exemplo n.º 16
0
Arquivo: smtp.go Projeto: 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
}
Exemplo n.º 17
0
func EncryptSign(privateKeyFileName string, readPass readPasswordCallback, publicKeyFileName string, plainTextFile string, cipherTextFile string) (err error) {

	var signer *openpgp.Entity
	if signer, err = readPrivateKeyFile(privateKeyFileName, readPass); err != nil {
		return err
	}

	var recipients openpgp.EntityList
	if recipients, err = readPublicKeyFile(publicKeyFileName); err != nil {
		return err
	}

	var plainTextInput *os.File
	if plainTextInput, err = os.Open(plainTextFile); err != nil {
		return err
	}
	defer plainTextInput.Close()

	inputStat, err := plainTextInput.Stat()
	if err != nil {
		return err
	}
	plainTextBytes := inputStat.Size()

	var cipherTextOutput *os.File
	if cipherTextOutput, err = os.Create(cipherTextFile); err != nil {
		return err
	}

	fHints := &openpgp.FileHints{
		IsBinary: true,
		FileName: path.Base(plainTextFile),
		ModTime:  inputStat.ModTime(),
	}

	var we io.WriteCloser
	if we, err = openpgp.Encrypt(cipherTextOutput, recipients, signer, fHints, nil); err != nil {
		return err
	}
	defer we.Close()

	copiedBytes, err := io.Copy(we, plainTextInput)
	if copiedBytes != plainTextBytes {
		return fmt.Errorf("encrypted only %d bytes out of %d", copiedBytes, plainTextBytes)
	}
	return nil
}
Exemplo n.º 18
0
func encryptEmail(e *Email) error {
	if len(e.OpenPGPEncryptTo) == 0 {
		return nil
	}

	buf := &bytes.Buffer{}
	var destEntities []*openpgp.Entity
	for _, eto := range e.OpenPGPEncryptTo {
		r := bytes.NewBufferString(eto)
		blk, err := armor.Decode(r)
		if err != nil {
			return err
		}

		rr := packet.NewReader(blk.Body)
		e, err := openpgp.ReadEntity(rr)
		if err != nil {
			return err
		}

		destEntities = append(destEntities, e)
	}

	aew, err := armor.Encode(buf, "PGP MESSAGE", map[string]string{
		"Version": "OpenPGP",
	})
	if err != nil {
		return err
	}

	wr, err := openpgp.Encrypt(aew, destEntities, nil, nil, nil)
	if err != nil {
		return err
	}

	_, err = wr.Write([]byte(e.Body))
	if err != nil {
		wr.Close()
		return err
	}

	wr.Close()
	aew.Close()

	e.Body = string(buf.Bytes())
	return nil
}
Exemplo n.º 19
0
func main() {
	//NewEntity("hyg", "*****@*****.**", "secfile.key")
	//return

	pubringFile, _ := os.Open("path to public keyring")
	defer pubringFile.Close()
	pubring, _ := openpgp.ReadKeyRing(pubringFile)
	//theirPublicKey := getKeyByEmail(pubring, "*****@*****.**")
	theirPublicKey := getKeyByEmail(pubring, "*****@*****.**")

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

	//theirPublicKey.Serialize(os.Stdout)
	//myPrivateKey.Serialize(os.Stdout)
	//myPrivateKey.SerializePrivate(os.Stdout, nil)

	myPrivateKey.PrivateKey.Decrypt([]byte("passphrase"))
	/*
		// bug: have to input the correct passphrase at the first time

		for myPrivateKey.PrivateKey.Encrypted {
			fmt.Print("PGP passphrase: ")
			pgppass := gopass.GetPasswd()

			myPrivateKey.PrivateKey.Decrypt([]byte(pgppass))
			if myPrivateKey.PrivateKey.Encrypted {
				fmt.Println("Incorrect. Try again or press ctrl+c to exit.")
			}
		}
	*/

	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")
}
Exemplo n.º 20
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()

}
Exemplo n.º 21
0
// EncryptMsg encrypts the message.
func (obj *PGP) EncryptMsg(to *openpgp.Entity, msg string) (*bytes.Buffer, error) {
	ents := []*openpgp.Entity{to}

	buf := new(bytes.Buffer)
	w, err := openpgp.Encrypt(buf, ents, obj.Entity, nil, nil)
	if err != nil {
		return nil, errwrap.Wrapf(err, "can't encrypt message")
	}

	_, err = w.Write([]byte(msg))
	if err != nil {
		return nil, errwrap.Wrapf(err, "can't write to buffer")
	}

	if err = w.Close(); err != nil {
		return nil, errwrap.Wrapf(err, "can't close writer")
	}
	return buf, nil
}
Exemplo n.º 22
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()

}
Exemplo n.º 23
0
Arquivo: sec.go Projeto: tslnc04/go-1
func Encrypt(s string) (string, error) {
	bstream := bytes.NewBufferString(PubKey())
	ring, err := openpgp.ReadArmoredKeyRing(bstream)
	if err != nil {
		return "", err
	}
	buf := new(bytes.Buffer)
	w, err := openpgp.Encrypt(buf, ring, nil, nil, nil)
	if err != nil {
		return "", err
	}
	w.Write([]byte(s))
	w.Close()
	bytes, err := ioutil.ReadAll(buf)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(bytes), nil
}
Exemplo n.º 24
0
func (o *openPGP) Encrypt(input *os.File, output *os.File, _ bool) (err error) {
	hints := &openpgp.FileHints{
		IsBinary: true,
		FileName: input.Name(),
		ModTime:  time.Now(),
	}

	// signing is automatically detected if SetKey(secKey) is performed on
	// the *openPGP instance

	pgpOut, err := openpgp.Encrypt(output, []*openpgp.Entity{o.pubKey}, o.secKey, hints, nil)

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

	_, err = io.Copy(pgpOut, input)

	return
}
Exemplo n.º 25
0
func maybeCrypt(r io.Reader) io.Reader {
	if len(encryptKeys) == 0 {
		return r
	}

	pr, pw := io.Pipe()
	go func() {
		w, err := openpgp.Encrypt(pw, encryptKeys, nil, nil, nil)
		if err != nil {
			pw.CloseWithError(err)
			return
		}
		_, err = io.Copy(w, r)
		if err != nil {
			pw.CloseWithError(err)
			return
		}
		pw.CloseWithError(w.Close())
	}()
	return pr
}
Exemplo n.º 26
0
// encryptMailBody retrieves the PGP fingerprint of a recipient from ldap, then
// queries the gpg server to retrieve the public key and encrypts the body with it.
func encryptMailBody(conf conf, origBody []byte, rcpt string) (body []byte, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("encryptMailBody-> %v", e)
		}
	}()
	key, err := conf.Ldap.cli.GetUserPGPKey("mail=" + rcpt)
	if err != nil {
		panic(err)
	}
	el, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(key))
	if err != nil {
		panic(err)
	}
	encbuf := new(bytes.Buffer)
	w, err := openpgp.Encrypt(encbuf, el, nil, nil, nil)
	if err != nil {
		panic(err)
	}
	_, err = w.Write([]byte(origBody))
	if err != nil {
		panic(err)
	}
	err = w.Close()
	if err != nil {
		panic(err)
	}
	armbuf := bytes.NewBuffer(nil)
	w, err = armor.Encode(armbuf, "PGP MESSAGE", nil)
	if err != nil {
		panic(err)
	}
	_, err = w.Write(encbuf.Bytes())
	if err != nil {
		panic(err)
	}
	w.Close()
	body = armbuf.Bytes()
	return
}
Exemplo n.º 27
0
// Encrypt a byte with the given publicKeyring
func Encrypt(b []byte, publicKeyring string) ([]byte, error) {
	// Read in public key
	keyringFileBuffer, err := os.Open(publicKeyring)
	if err != nil {
		return nil, fmt.Errorf("opening public key %s failed: %v", publicKeyring, err)
	}
	defer keyringFileBuffer.Close()

	entityList, err := openpgp.ReadKeyRing(keyringFileBuffer)
	if err != nil {
		return nil, err
	}

	// encrypt string
	buf := new(bytes.Buffer)
	w, err := openpgp.Encrypt(buf, entityList, nil, nil, nil)
	if err != nil {
		return nil, err
	}
	defer w.Close()

	// write the byte to our encrypt writer
	if _, err = w.Write(b); err != nil {
		return nil, err
	}

	// close the writer
	if err = w.Close(); err != nil {
		return nil, err
	}

	bytes, err := ioutil.ReadAll(buf)
	if err != nil {
		return nil, err
	}

	// base64 encode
	encStr := base64.StdEncoding.EncodeToString(bytes)
	return []byte(encStr), nil
}
Exemplo n.º 28
0
func encode(data []byte, entityList openpgp.EntityList) ([]byte, error) {
	buffer := new(bytes.Buffer)
	encoder := base64.NewEncoder(base64.StdEncoding, buffer)
	pgpWriter, err := openpgp.Encrypt(encoder, entityList, nil, &openpgp.FileHints{IsBinary: true, FileName: "_CONSOLE"}, 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.º 29
0
// EncryptMessage creates ciphertext based upon `message`, sent from
// `sender` to `recipient`, then writes it to `dst`
func EncryptMessage(mw io.Writer, sender, recipient, msg string) error {
	defer func() {
		if err := recover(); err != nil {
			log.Println("Error in encryptMessage:", err)
			log.Fatalf("(That probably meant that you don't have %s's key)\n",
				recipient)
		}
	}()
	// Grab relevant keys
	myPrivateKey, err := GetEntityFrom(sender, PRIVATE_KEYRING_FILENAME)
	if err != nil {
		return fmt.Errorf("Error getting private key for %s from %s: %v",
			sender, PRIVATE_KEYRING_FILENAME, err)
	}
	theirPublicKey, err := GetEntityFrom(recipient, PUBLIC_KEYRING_FILENAME)
	if err != nil {
		return fmt.Errorf("Error getting public key for %s from %s: %v",
			recipient, PRIVATE_KEYRING_FILENAME, err)
	}

	// Produce new writer to... write encrypted messages to?
	w, err := armor.Encode(mw, "PGP MESSAGE", nil)
	if err != nil {
		return fmt.Errorf("Error from armor.Encode: %v", err)
	}
	defer w.Close()

	// Encrypt message from ME to recipient
	plaintext, err := openpgp.Encrypt(w, []*openpgp.Entity{theirPublicKey},
		myPrivateKey, nil, nil)
	if err != nil {
		return fmt.Errorf("Error from openpgp.Encrypt: %v", err)
	}
	defer plaintext.Close()

	// Write message to `plaintext` WriteCloser
	_, err = fmt.Fprintf(plaintext, msg)
	return err
}
Exemplo n.º 30
0
// Encrypt encrypts a message
func (g *Gpg) Encrypt(b []byte) ([]byte, error) {
	log.Printf("[DEBUG] GPG Open public keyring %s", g.PublicKeyring)
	publicRingBuffer, err := os.Open(g.PublicKeyring)
	if err != nil {
		return nil, fmt.Errorf(
			"opening public key %s failed: %v", g.PublicKeyring, err)
	}
	defer publicRingBuffer.Close()
	log.Printf("[DEBUG] GPG Read public keyring")
	publicRing, err := openpgp.ReadKeyRing(publicRingBuffer)
	if err != nil {
		return nil, err
	}
	publicKey := getKeyByEmail(publicRing, g.Email)
	if publicKey == nil {
		return nil, fmt.Errorf("Can't find GPG public key")
	}

	var buffer = &bytes.Buffer{}
	armoredWriter, err := armor.Encode(buffer, "PGP MESSAGE", nil)
	if err != nil {
		return nil, err
	}
	cipheredWriter, err := openpgp.Encrypt(
		armoredWriter, []*openpgp.Entity{publicKey}, nil, nil, nil)
	if err != nil {
		return nil, err
	}
	_, err = cipheredWriter.Write(b)
	if err != nil {
		return nil, err
	}

	cipheredWriter.Close()
	armoredWriter.Close()

	return buffer.Bytes(), nil

}