示例#1
0
// Encrypt the provided bytes for the provided encryption
// keys recipients. Returns the encrypted content bytes.
func Encrypt(d []byte, encryptionKeys *openpgp.EntityList) ([]byte, error) {
	var buffer *bytes.Buffer = &bytes.Buffer{}
	var armoredWriter io.WriteCloser
	var cipheredWriter io.WriteCloser
	var err error

	// Create an openpgp armored cipher writer pointing on our
	// buffer
	armoredWriter, err = armor.Encode(buffer, "PGP MESSAGE", nil)
	if err != nil {
		return nil, NewPgpError(ERR_ENCRYPTION_ENCODING, fmt.Sprintf("Can't make armor: %v", err))
	}

	// Create an encrypted writer using the provided encryption keys
	cipheredWriter, err = openpgp.Encrypt(armoredWriter, *encryptionKeys, nil, nil, nil)
	if err != nil {
		return nil, NewPgpError(ERR_ENCRYPTION_ENCRYPT, fmt.Sprintf("Error encrypting: %v", err))
	}

	// Write (encrypts on the fly) the provided bytes to
	// cipheredWriter
	_, err = cipheredWriter.Write(d)
	if err != nil {
		return nil, NewPgpError(ERR_ENCRYPTION_ENCRYPT, fmt.Sprintf("Error copying encrypted content: %v", err))
	}

	cipheredWriter.Close()
	armoredWriter.Close()

	return buffer.Bytes(), nil
}
示例#2
0
文件: encrypt.go 项目: nymsio/pgpmail
func encryptWith(m *Message, pubkeys openpgp.EntityList, signingEntity *openpgp.Entity, passphrase string) *EncryptStatus {
	if len(pubkeys) == 0 {
		return createEncryptFailure("no recipient keys")
	}
	buffer := new(bytes.Buffer)
	ar, err := armor.Encode(buffer, "PGP MESSAGE", nil)
	if err != nil {
		return createEncryptFailure("error encoding output message: " + err.Error())
	}
	if signingEntity.PrivateKey == nil {
		return createEncryptFailure("signing key has no private key")
	}
	if signingEntity != nil && isSigningKeyLocked(signingEntity, passphrase) {
		return &EncryptStatus{Code: StatusFailedPassphraseNeeded}
	}
	w, err := openpgp.Encrypt(ar, pubkeys, signingEntity, nil, openpgpConfig)
	if err != nil {
		return createEncryptFailure("encryption operation failed: " + err.Error())
	}
	bodyPart := createBodyMimePart(m)
	w.Write(bodyPart.rawContent)
	w.Close()
	ar.Close()
	buffer.WriteString("\n")
	err = writeEncryptedMimeBody(m, buffer.Bytes())
	if err != nil {
		return createEncryptFailure(err.Error())
	}
	if signingEntity != nil {
		return &EncryptStatus{Code: StatusSignedAndEncrypted, Message: m}
	} else {
		return &EncryptStatus{Code: StatusEncryptedOnly, Message: m}
	}
}
示例#3
0
func encryptMail(e Envelope, keys openpgp.EntityList) (*bytes.Buffer, error) {
	var err error
	var contenttype string
	var buffer *bytes.Buffer
	var armored io.WriteCloser
	var crypter io.WriteCloser

	buffer = bytes.NewBuffer(nil)

	armored, err = armor.Encode(buffer, "PGP MESSAGE", nil)
	if err != nil {
		return buffer, err
	}

	crypter, err = openpgp.Encrypt(armored, keys, nil, nil, nil)
	if err != nil {
		return buffer, err
	}

	contenttype = e.Mail.Header.Get("Content-Type")
	if contenttype == "" {
		contenttype = "text/plain"
	}
	fmt.Fprintf(crypter, "Content-Type: %s\n\n", contenttype)

	io.Copy(crypter, e.Mail.Body)
	crypter.Close()
	armored.Close()

	return buffer, nil
}
示例#4
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
}
示例#5
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
}
示例#6
0
文件: common.go 项目: jgrocho/pass
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
}
示例#7
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")
}
示例#8
0
func (g *GpgEncrypt) EncryptStringToFile(plaintext string, sPath string, sEmail string) error {
	rcptPubKey := g.GetKeyByEmail(g.entityList, sEmail)

	buf := new(bytes.Buffer)
	w, err := openpgp.Encrypt(buf, []*openpgp.Entity{rcptPubKey}, nil, nil, nil)
	if err != nil {
		return err
	}
	_, err = w.Write([]byte(plaintext))
	if err != nil {
		return err
	}
	err = w.Close()
	if err != nil {
		return err
	}
	return ioutil.WriteFile(sPath, buf.Bytes(), 0666)
}
示例#9
0
文件: upload_crypto.go 项目: 40a/cbfs
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
}
示例#10
0
func encryptForUsers(plaintext string, addrs []string) string {
	keys := make([]*openpgp.Entity, 0)
	for _, addr := range addrs {
		token := strings.Split(addr, "@")[0]
		user := LoadUser(token)
		if user == nil {
			// we've already told the SMTP sender that those
			// recipients don't exist on this server
			continue
		}

		entity, err := ReadEntity(user.PublicKey)
		if err != nil {
			panic(err)
		}
		keys = append(keys, entity)
	}
	if len(keys) == 0 {
		log.Printf("Warning: not encrypting incoming mail--unrecognized recipients")
		return plaintext
	}
	log.Printf("Encrypting plaintext for %s, found %d keys\n",
		strings.Join(addrs, ","), len(keys))

	cipherBuffer := new(bytes.Buffer)
	w, err := armor.Encode(cipherBuffer, "PGP MESSAGE", nil)
	if err != nil {
		panic(err)
	}
	plainWriter, err := openpgp.Encrypt(w, keys, nil, nil, nil)
	if err != nil {
		panic(err)
	}
	plainWriter.Write([]byte(plaintext))
	plainWriter.Close()
	w.Close()

	ciphertext := cipherBuffer.String()
	return ciphertext
}
示例#11
0
func encrypt(s string) string {
	buf := &bytes.Buffer{}

	wa, err := armor.Encode(buf, "PGP MESSAGE", nil)
	if err != nil {
		log.Fatalf("Can't make armor: %v", err)
	}

	w, err := openpgp.Encrypt(wa, encryptKeys, nil, nil, nil)
	if err != nil {
		log.Fatalf("Error encrypting: %v", err)
	}
	_, err = io.Copy(w, strings.NewReader(s))
	if err != nil {
		log.Fatalf("Error encrypting: %v", err)
	}

	w.Close()
	wa.Close()

	return buf.String()
}
示例#12
0
func Encrypt(encryptionKeys *openpgp.EntityList, s string) []byte {
	buf := &bytes.Buffer{}

	wa, err := armor.Encode(buf, "PGP MESSAGE", nil)
	if err != nil {
		NewPgpError(ERR_ENCRYPTION_ENCODING, fmt.Sprintf("Can't make armor: %v", err))
	}

	w, err := openpgp.Encrypt(wa, *encryptionKeys, nil, nil, nil)
	if err != nil {
		NewPgpError(ERR_ENCRYPTION_ENCRYPT, fmt.Sprintf("Error encrypting: %v", err))
	}

	_, err = io.Copy(w, strings.NewReader(s))
	if err != nil {
		log.Fatalf("Error copying encrypted content: %v", err)
	}

	w.Close()
	wa.Close()

	return buf.Bytes()
}
示例#13
0
func encodeBase64EncryptedMessage(s string, entitylist openpgp.EntityList) string {
	// Encrypt message using public key and then encode with base64
	debug.Printf("entitylist: #%v", entitylist)
	buf := new(bytes.Buffer)
	w, err := openpgp.Encrypt(buf, entitylist, nil, nil, nil)
	if err != nil {
		log.Fatalln("ERR: Error encrypting message - ", err)
	}

	_, err = w.Write([]byte(s))
	if err != nil {
	}
	err = w.Close()
	if err != nil {
	}

	// Output as base64 encoded string
	bytes, err := ioutil.ReadAll(buf)
	str := base64.StdEncoding.EncodeToString(bytes)

	debug.Printf("Public key encrypted message (base64 encoded): %v", str)

	return str
}
示例#14
0
文件: upload.go 项目: bfix/sid
/*
 * Client upload data received.
 * @param data []byte - uploaded document data
 * @return bool - post-processing successful?
 */
func PostprocessUploadData(data []byte) bool {

	logger.Println(logger.INFO, "[sid.upload] Client upload received")
	logger.Println(logger.DBG_ALL, "[sid.upload] Client upload data:\n"+string(data))

	baseName := uploadPath + "/" + CreateId(16)

	// check if we use a shared secret scheme
	if reviewer == nil {
		// no: store content unencrypted.
		fname := baseName + ".document"
		wrt, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
		if err != nil {
			logger.Printf(logger.ERROR, "[sid.upload] Can't create document file '%s'\n", fname)
			return false
		}
		// write content and close file
		wrt.Write(data)
		wrt.Close()
	} else {
		// yes: use shared secret scheme to store upload in encrypted form.
		var (
			err    error
			engine cipher.Block   = nil
			wrt    io.WriteCloser = nil
			ct     io.WriteCloser = nil
			pt     io.WriteCloser = nil
		)

		//-----------------------------------------------------------------
		// setup AES-256 for encryption
		//-----------------------------------------------------------------
		key := crypto.RandBytes(32)
		if engine, err = aes.NewCipher(key); err != nil {
			// should not happen at all; epic fail if it does
			logger.Println(logger.ERROR, "[sid.upload] Failed to setup AES cipher!")
			return false
		}
		bs := engine.BlockSize()
		iv := crypto.RandBytes(bs)
		enc := cipher.NewCFBEncrypter(engine, iv)

		logger.Println(logger.DBG_ALL, "[sid.upload] key:\n"+hex.Dump(key))
		logger.Println(logger.DBG_ALL, "[sid.upload] IV:\n"+hex.Dump(iv))

		//-----------------------------------------------------------------
		// encrypt client document into file
		//-----------------------------------------------------------------

		// open file for output
		fname := baseName + ".document.aes256"
		if wrt, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666); err != nil {
			logger.Printf(logger.ERROR, "[sid.upload] Can't create document file '%s'\n", fname)
			return false
		}
		// write iv first
		wrt.Write(iv)
		// encrypt binary data for the document
		logger.Println(logger.DBG_ALL, "[sid.upload] AES256 in:\n"+hex.Dump(data))
		enc.XORKeyStream(data, data)
		logger.Println(logger.DBG_ALL, "[sid.upload] AES256 out:\n"+hex.Dump(data))
		// write to file
		wrt.Write(data)
		wrt.Close()

		//-----------------------------------------------------------------
		//	create shares from secret
		//-----------------------------------------------------------------
		secret := new(big.Int).SetBytes(key)
		n := len(reviewer)
		shares := crypto.Split(secret, prime, n, treshold)
		recipient := make([]*openpgp.Entity, 1)

		for i, ent := range reviewer {
			// generate filename based on key id
			id := strconv.FormatUint(ent.PrimaryKey.KeyId&0xFFFFFFFF, 16)
			fname = baseName + "." + strings.ToUpper(id) + ".gpg"
			// create file for output
			if wrt, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666); err != nil {
				logger.Printf(logger.ERROR, "[sid.upload] Can't create share file '%s'\n", fname)
				continue
			}
			// create PGP armorer
			if ct, err = armor.Encode(wrt, "PGP MESSAGE", nil); err != nil {
				logger.Printf(logger.ERROR, "[sid.upload] Can't create armorer: %s\n", err.Error())
				wrt.Close()
				continue
			}
			// encrypt share to file
			recipient[0] = ent
			if pt, err = openpgp.Encrypt(ct, recipient, nil, nil, nil); err != nil {
				logger.Printf(logger.ERROR, "[sid.upload] Can't create encrypter: %s\n", err.Error())
				ct.Close()
				wrt.Close()
				continue
			}
			pt.Write([]byte(shares[i].P.String() + "\n"))
			pt.Write([]byte(shares[i].X.String() + "\n"))
			pt.Write([]byte(shares[i].Y.String() + "\n"))
			pt.Close()
			ct.Close()
			wrt.Close()
		}
	}
	// report success
	return true
}