Example #1
0
File: pgp.go Project: igofman/mig
func GenerateKeyPair(name, desc, email string) (pubkey, privkey []byte, fp string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("GenerateKeyPair() -> %v", e)
		}
	}()
	// generate a private key
	ent, err := openpgp.NewEntity(name, desc, email, nil)
	if err != nil {
		panic(err)
	}
	// serialize the private key
	pkbuf := bytes.NewBuffer(nil)
	err = ent.SerializePrivate(pkbuf, nil)
	if err != nil {
		panic(err)
	}
	buf := bytes.NewBuffer(nil)
	ewrbuf, err := armor.Encode(buf, openpgp.PrivateKeyType, nil)
	if err != nil {
		panic(err)
	}
	_, err = ewrbuf.Write(pkbuf.Bytes())
	if err != nil {
		panic(err)
	}
	ewrbuf.Close()
	privkey = buf.Bytes()
	// serialize the public key
	pkbuf = bytes.NewBuffer(nil)
	err = ent.Serialize(pkbuf)
	if err != nil {
		panic(err)
	}
	buf = bytes.NewBuffer(nil)
	ewrbuf, err = armor.Encode(buf, openpgp.PublicKeyType, nil)
	if err != nil {
		panic(err)
	}
	_, err = ewrbuf.Write(pkbuf.Bytes())
	if err != nil {
		panic(err)
	}
	ewrbuf.Close()
	pubkey = buf.Bytes()
	// validate the public key and obtain a fingerprint from it
	fp, err = LoadArmoredPubKey(pubkey)
	if err != nil {
		panic(err)
	}
	return
}
Example #2
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
}
Example #3
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
}
Example #4
0
// Export writes out the named public key, or all public keys if keyID
// is empty. The result is an ASCII-armoured public key.
func (keyRing *KeyRing) Export(keyID string) (armoured string, err error) {
	buf := new(bytes.Buffer)
	blockType := openpgp.PublicKeyType
	blockHeaders := map[string]string{
		"Version": fmt.Sprintf("Keybase Go client (OpenPGP version %s)", Version),
	}

	armourBuffer, err := armor.Encode(buf, blockType, blockHeaders)
	if err != nil {
		return
	}

	if keyID != "" {
		e, ok := keyRing.Entities[strings.ToLower(keyID)]
		if !ok {
			err = ErrKeyNotFound
			return
		}
		e.Serialize(armourBuffer)
	} else {
		if len(keyRing.Entities) == 0 {
			err = ErrKeyNotFound
			return
		}
		for _, e := range keyRing.Entities {
			e.Serialize(armourBuffer)
		}
	}

	armourBuffer.Close()

	armoured = string(buf.Bytes())
	return
}
Example #5
0
// NewEntity creates a new entity. It doesn't provide an option for comments.
func NewEntity(name, email, outFile string) (ne *openpgp.Entity, err error) {
	ne, err = openpgp.NewEntity(name, "", email, nil)
	if err != nil {
		return
	}

	out, err := os.Create(outFile)
	if err != nil {
		ne = nil
		return
	}

	hdr := map[string]string{
		"Version": "Keybase Go client (OpenPGP version v0.1)",
	}

	keyOut, err := armor.Encode(out, openpgp.PrivateKeyType, hdr)
	if err != nil {
		ne = nil
		return
	}

	defer func() {
		keyOut.Close()
		out.Close()
	}()

	err = ne.SerializePrivate(keyOut, nil)
	if err != nil {
		ne = nil
		return
	}

	return
}
Example #6
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

}
Example #7
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 #8
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 #9
0
func (d *dashEscaper) Close() (err error) {
	if !d.atBeginningOfLine {
		if err = d.buffered.WriteByte(lf); err != nil {
			return
		}
	}
	sig := new(packet.Signature)
	sig.SigType = packet.SigTypeText
	sig.PubKeyAlgo = d.privateKey.PubKeyAlgo
	sig.Hash = d.hashType
	sig.CreationTime = d.config.Now()
	sig.IssuerKeyId = &d.privateKey.KeyId

	if err = sig.Sign(d.h, d.privateKey, d.config); err != nil {
		return
	}

	out, err := armor.Encode(d.buffered, "PGP SIGNATURE", nil)
	if err != nil {
		return
	}

	if err = sig.Serialize(out); err != nil {
		return
	}
	if err = out.Close(); err != nil {
		return
	}
	if err = d.buffered.Flush(); err != nil {
		return
	}
	return
}
Example #10
0
func ExportKey(key, filename string) error {
	entity, err := findKey(key)
	if err != nil {
		return err
	}

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

	w, err := armor.Encode(f, openpgp.PublicKeyType, nil)
	if err != nil {
		return err
	}

	err = entity.Serialize(w)
	if err != nil {
		return err
	}

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

	return nil
}
Example #11
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 #12
0
func writePrivateKeyToFile(entity *openpgp.Entity, privateKeyFile string) error {
	privKey, err := os.OpenFile(privateKeyFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0400)
	if err != nil {
		return err
	}
	w, err := armor.Encode(
		privKey,
		openpgp.PrivateKeyType,
		map[string]string{
			"Comment": "Key pair generated by generic worker",
		},
	)
	if err != nil {
		return err
	}
	defer func() {
		w.Close()
		fmt.Fprintln(privKey)
		privKey.Close()
	}()
	err = entity.SerializePrivate(w, nil)
	if err != nil {
		return err
	}
	return nil
}
Example #13
0
File: openpgp.go Project: bndw/pick
// encrypt uses PGP to symmetrically encrypt and armor text with the
// provided password.
func (c *OpenPGPClient) Encrypt(plaintext []byte, password []byte) (ciphertext []byte, err error) {
	encbuf := bytes.NewBuffer(nil)

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

	pt, err := openpgp.SymmetricallyEncrypt(w, password, nil, c.packetConfig)
	if err != nil {
		return
	}
	defer pt.Close()

	if _, err := pt.Write(plaintext); err != nil {
		return nil, err
	}

	// Force-close writer to flush their cache
	if err = pt.Close(); err != nil {
		return
	}
	if err = w.Close(); err != nil {
		return
	}

	ciphertext = encbuf.Bytes()
	return
}
Example #14
0
func (o *openPGP) GenKey(identifier string, email string) (pubKey string, secKey string, err error) {
	buf := bytes.NewBuffer(nil)
	header := map[string]string{
		"Version": fmt.Sprintf("INTERLOCK %s OpenPGP generated key", InterlockVersion),
	}

	entity, err := openpgp.NewEntity(identifier, "", email, nil)

	if err != nil {
		return
	}

	encoder, err := armor.Encode(buf, openpgp.PublicKeyType, header)

	if err != nil {
		return
	}

	// we use our own function due to issues in openpgp.Serialize (see Serialize() comments)
	err = serialize(entity, encoder, nil)

	if err != nil {
		return
	}

	encoder.Close()
	pubKey = buf.String()

	buf.Reset()
	encoder, err = armor.Encode(buf, openpgp.PrivateKeyType, header)

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

	err = entity.SerializePrivate(encoder, nil)

	if err != nil {
		return
	}

	encoder.Close()
	secKey = buf.String()

	return
}
Example #15
0
// Sign signs the given message.
func (keyRing *KeyRing) Sign(message []byte, keyID string) (sig []byte, err error) {
	err = keyRing.Unlock(keyID)
	if err != nil {
		return
	}

	signer := keyRing.Entities[strings.ToLower(keyID)]
	buf := new(bytes.Buffer)
	hdr := map[string]string{
		"Version": fmt.Sprintf("Keybase Go client (OpenPGP version %s)", Version),
	}
	armourBuf, err := armor.Encode(buf, "PGP MESSAGE", hdr)
	if err != nil {
		return
	}

	opSig := &packet.OnePassSignature{
		SigType:    packet.SigTypeBinary,
		Hash:       crypto.SHA1,
		PubKeyAlgo: packet.PubKeyAlgoRSA,
		KeyId:      signer.PrimaryKey.KeyId,
		IsLast:     true,
	}
	err = opSig.Serialize(armourBuf)
	if err != nil {
		return
	}

	literalPacket, err := newLiteralDataPacket(message, "", uint32(time.Now().Unix()))
	if err != nil {
		return
	}
	_, err = armourBuf.Write(literalPacket)
	if err != nil {
		return
	}

	sigPacket := &packet.Signature{
		SigType:      packet.SigTypeBinary,
		IssuerKeyId:  &signer.PrimaryKey.KeyId,
		PubKeyAlgo:   packet.PubKeyAlgoRSA,
		Hash:         crypto.SHA1,
		CreationTime: time.Now(),
	}
	h := sha1.New()
	h.Write(message)
	err = sigPacket.Sign(h, signer.PrivateKey, nil)
	if err != nil {
		return
	}

	err = sigPacket.Serialize(armourBuf)
	if err != nil {
		return
	}
	armourBuf.Close()
	sig = buf.Bytes()
	return
}
Example #16
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)
}
Example #17
0
func (h *HKPFront) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	if r.Method != "GET" || r.URL.Path != "/pks/lookup" || len(q["op"]) != 1 || q["op"][0] != "get" || len(q["search"]) != 1 {
		http.Error(w, `this server only supports queries of the form "/pks/lookup?op=get&search=<EMAIL>"`, 501)
		return
	}
	user := q["search"][0]
	ctx := context.Background()

	var requiredSignatures *proto.QuorumExpr
	if !h.InsecureSkipVerify {
		realm, err := coname.GetRealmByUser(h.Config, user)
		if err != nil {
			http.Error(w, err.Error(), 400)
			return
		}
		requiredSignatures = realm.VerificationPolicy.Quorum
	}

	pf, err := h.Lookup(ctx, &proto.LookupRequest{UserId: user, QuorumRequirement: requiredSignatures})
	if err != nil {
		http.Error(w, err.Error(), 503)
		return
	}

	if !h.InsecureSkipVerify {
		coname.VerifyLookup(h.Config, user, pf, h.Clk.Now())
	}

	if pf.Profile.Keys == nil {
		http.Error(w, `No results found: No keys found: unknown email`, 404)
		return
	}

	pgpKey, present := pf.Profile.Keys["pgp"]
	if !present {
		http.Error(w, `No results found: No keys found: the email is known to the keyserver, but the profile does not include an OpenPGP key`, 404)
		return
	}

	if _, mr := q["mr"]; mr {
		w.Header().Set("Content-Type", "application/pgp-keys")
	}
	aw, err := armor.Encode(w, "PGP PUBLIC KEY BLOCK", nil)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	_, err = aw.Write(pgpKey)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	if err := aw.Close(); err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
}
Example #18
0
func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
	out, err := armor.Encode(w, SignatureType, nil)
	if err != nil {
		return
	}
	err = detachSign(out, signer, message, sigType, config)
	if err != nil {
		return
	}
	return out.Close()
}
Example #19
0
// Armor - this function returns the public part of our armored key.
// @return string - This is our public key
// @return error - An error can be produced when trying to access an unarmored string.
func (key *Key) Armor() (string, error) {
	buf := new(bytes.Buffer)
	armor, err := armor.Encode(buf, openpgp.PublicKeyType, nil)
	if err != nil {
		return "", err
	}
	key.Serialize(armor)
	armor.Close()

	return buf.String(), nil
}
Example #20
0
func GpgEncrypt(text2encrypt string, headers map[string]string) string {
	var encrypted bytes.Buffer
	foo := bufio.NewWriter(&encrypted)
	w, _ := armor.Encode(foo, "TRIBES PAYLOAD", headers)
	plaintext, _ := openpgp.SymmetricallyEncrypt(w, []byte(config.GetTribeID()), nil, nil)
	fmt.Fprintf(plaintext, text2encrypt)
	plaintext.Close()
	w.Close()
	foo.Flush()
	return encrypted.String()
}
Example #21
0
// ArmorPrivate - this function returns the private part of our armored key.
// @return string - This is our private key
// @return error - An error can be produced when trying to access an unarmored string.
func (key *Key) ArmorPrivate(config *Config) (string, error) {
	buf := new(bytes.Buffer)
	armor, err := armor.Encode(buf, openpgp.PrivateKeyType, nil)
	if err != nil {
		return "", err
	}
	c := config.Config
	key.SerializePrivate(armor, &c)
	armor.Close()

	return buf.String(), nil
}
Example #22
0
// GetArmoredPublicKey returns an armored public key for entity.
func GetArmoredPublicKey(ent *openpgp.Entity) ([]byte, error) {
	out := new(bytes.Buffer)
	wrt, err := armor.Encode(out, openpgp.PublicKeyType, nil)
	if err != nil {
		return nil, err
	}
	err = ent.Serialize(wrt)
	wrt.Close()
	if err != nil {
		return nil, err
	}
	return out.Bytes(), nil
}
Example #23
0
func Public(entity *openpgp.Entity) (string, error) {
	var output bytes.Buffer
	writeBuffer := bufio.NewWriter(&output)
	public, err := armor.Encode(writeBuffer, openpgp.PublicKeyType, nil)
	if err != nil {
		log.PrintError("telem.crypto.Public", err)
		return "", err
	}

	entity.Serialize(public)
	public.Close()
	writeBuffer.Flush()
	return output.String(), nil
}
Example #24
0
func Private(entity *openpgp.Entity) (string, error) {
	var output bytes.Buffer
	writeBuffer := bufio.NewWriter(&output)
	private, err := armor.Encode(writeBuffer, openpgp.PrivateKeyType, nil)
	if err != nil {
		log.PrintError("authit.crypto.Private", err)
		return "", err
	}

	entity.SerializePrivate(private, nil)
	private.Close()
	writeBuffer.Flush()
	return output.String(), nil
}
Example #25
0
File: pgp.go Project: lbn/gorwell
func ToArmor(secret []byte, blockType BlockType) []byte {
	buf := new(bytes.Buffer)
	w, err := armor.Encode(buf, string(blockType), nil)
	if err != nil {
		panic(err)
	}
	_, err = w.Write(secret)
	if err != nil {
		panic(err)
	}
	w.Close()
	bytes, _ := ioutil.ReadAll(buf)
	return bytes
}
Example #26
0
File: io.go Project: squeed/openpgp
func WriteArmoredPackets(w io.Writer, roots []*PrimaryKey) error {
	armw, err := armor.Encode(w, openpgp.PublicKeyType, nil)
	defer armw.Close()
	if err != nil {
		return errgo.Mask(err)
	}
	for _, node := range roots {
		err = WritePackets(armw, node)
		if err != nil {
			return errgo.Mask(err)
		}
	}
	return nil
}
Example #27
0
// EncryptDataArmored encrypts data using symmetric OpenPGP encryption.
// The result will be armored OpenPGP output.
func EncryptDataArmored(input []byte, password string) []byte {
	var output bytes.Buffer
	encryptedInput := EncryptData(input, password)

	armorWriter, err := armor.Encode(&output, "PGP MESSAGE", nil)
	PanicIfErr(err)

	_, err = armorWriter.Write(encryptedInput)
	PanicIfErr(err)

	err = armorWriter.Close()
	PanicIfErr(err)

	return output.Bytes()
}
Example #28
0
func testKeyring(opkr *openpgp.OpaqueKeyring) (int, int, error) {
	var buf bytes.Buffer
	for _, op := range opkr.Packets {
		err := op.Serialize(&buf)
		if err != nil {
			return 0, 0, errgo.Mask(err)
		}
	}
	pk, err := opkr.Parse()
	if err != nil {
		return 0, 0, errgo.Mask(err)
	}
	dupDigest, err := openpgp.SksDigest(pk, md5.New())
	if err != nil {
		return 0, 0, errgo.Mask(err)
	}

	err = openpgp.DropDuplicates(pk)
	if err != nil {
		return 0, 0, errgo.Mask(err)
	}
	dedupDigest, err := openpgp.SksDigest(pk, md5.New())
	if err != nil {
		return 0, 0, errgo.Mask(err)
	}
	cmd := exec.Command("./sks_hash")
	var out bytes.Buffer
	cmd.Stdin = bytes.NewBuffer(buf.Bytes())
	cmd.Stdout = &out
	err = cmd.Run()
	if err != nil {
		return 0, 0, errgo.Mask(err)
	}
	sksDigest := strings.ToLower(strings.TrimSpace(string(out.Bytes())))
	if dedupDigest != sksDigest {
		log.Warningf("hkp=%q hkp_dedup=%q sks=%q", dupDigest, dedupDigest, sksDigest)
		var out bytes.Buffer
		armw, err := armor.Encode(&out, xopenpgp.PublicKeyType, nil)
		if err != nil {
			return 0, 1, errgo.Mask(err)
		}
		armw.Write(buf.Bytes())
		armw.Close()
		fmt.Println(out.String())
		return 0, 1, nil
	}
	return 1, 0, nil
}
Example #29
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 #30
0
func ArmoredPublicKey(entity *openpgp.Entity) (string, error) {
	var buf bytes.Buffer
	wc, err := armor.Encode(&buf, openpgp.PublicKeyType, nil)
	if err != nil {
		return "", err
	}
	err = entity.PrivateKey.PublicKey.Serialize(wc)
	if err != nil {
		return "", err
	}
	wc.Close()
	if !bytes.HasSuffix(buf.Bytes(), newlineBytes) {
		buf.WriteString("\n")
	}
	return buf.String(), nil
}