func ExampleNewEncryptArmor62Stream() {

	var err error

	// Make a new Keyring, initialized to be empty
	keyring := basic.NewKeyring()

	// The test message
	plaintext := "The Magic Words are Squeamish Ossifrage"

	// Make a secret key for the sender
	var sender saltpack.BoxSecretKey
	sender, err = keyring.GenerateBoxKey()
	if err != nil {
		return
	}

	// And one for the receiver
	var receiver saltpack.BoxSecretKey
	receiver, err = keyring.GenerateBoxKey()
	if err != nil {
		return
	}

	// AllReceivers can contain more receivers (like the sender)
	// but for now, just the one.
	var output bytes.Buffer
	allReceivers := []saltpack.BoxPublicKey{receiver.GetPublicKey()}
	var input io.WriteCloser
	input, err = saltpack.NewEncryptArmor62Stream(&output, sender, allReceivers, "")
	if err != nil {
		return
	}
	// Write plaintext into the returned WriteCloser stream
	input.Write([]byte(plaintext))
	// And close when we're done
	input.Close()

	// The decrypted message
	var plaintextOutput io.Reader
	_, plaintextOutput, _, err = saltpack.NewDearmor62DecryptStream(&output, keyring)
	if err != nil {
		return
	}

	// Copy all of the data out of the output decrypted stream, and into standard
	// output, here for testing / comparison purposes.
	io.Copy(os.Stdout, plaintextOutput)
	os.Stdout.Write([]byte{'\n'})

	// Output:
	// The Magic Words are Squeamish Ossifrage
}
Exemple #2
0
func SaltpackDecrypt(
	g *GlobalContext, source io.Reader, sink io.WriteCloser,
	deviceEncryptionKey NaclDHKeyPair,
	checkSender func(*saltpack.MessageKeyInfo) error) (*saltpack.MessageKeyInfo, error) {

	sc, newSource, err := ClassifyStream(source)
	if err != nil {
		return nil, err
	}

	if sc.Format != CryptoMessageFormatSaltpack {
		return nil, WrongCryptoFormatError{
			Wanted:    CryptoMessageFormatSaltpack,
			Received:  sc.Format,
			Operation: "decrypt",
		}
	}

	source = newSource

	var mki *saltpack.MessageKeyInfo
	var plainsource io.Reader
	var frame saltpack.Frame
	if sc.Armored {
		mki, plainsource, frame, err = saltpack.NewDearmor62DecryptStream(source, naclKeyring(deviceEncryptionKey))
	} else {
		mki, plainsource, err = saltpack.NewDecryptStream(source, naclKeyring(deviceEncryptionKey))
	}

	if err != nil {
		return mki, err
	}

	if checkSender != nil {
		if err = checkSender(mki); err != nil {
			return mki, err
		}
	}

	n, err := io.Copy(sink, plainsource)
	if err != nil {
		return mki, err
	}

	// TODO: Check header inline, and only warn if the footer
	// doesn't match.
	if sc.Armored {
		var brand string
		brand, err = saltpack.CheckArmor62Frame(frame, saltpack.MessageTypeEncryption)
		if err != nil {
			return mki, err
		}
		if err = checkSaltpackBrand(brand); err != nil {
			return mki, err
		}
	}

	g.Log.Debug("Decrypt: read %d bytes", n)

	if err := sink.Close(); err != nil {
		return mki, err
	}
	return mki, nil
}