Example #1
0
// Encrypts a plaintext message with a temporary key and IV.
func (m *Message) Encrypt() error {
	// Generate a new temporary key and the associated block cipher
	key := make([]byte, config.PacketCipherBits/8)
	if n, err := io.ReadFull(rand.Reader, key); n != len(key) || err != nil {
		return err
	}
	block, err := config.PacketCipher(key)
	if err != nil {
		return err
	}
	// Generate a new random counter mode IV and the associated stream cipher
	iv := make([]byte, block.BlockSize())
	if n, err := io.ReadFull(rand.Reader, iv); n != len(iv) || err != nil {
		return err
	}
	stream := cipher.NewCTR(block, iv)

	// Encrypt the message, save the nonces and return
	stream.XORKeyStream(m.Data, m.Data)
	m.Head.Key = key
	m.Head.Iv = iv

	m.secure = true
	return nil
}
Example #2
0
// Decrypts a ciphertext message using the given key and IV.
func (m *Message) Decrypt() error {
	// Create the stream cipher for decryption
	block, err := config.PacketCipher(m.Head.Key)
	if err != nil {
		return err
	}
	stream := cipher.NewCTR(block, m.Head.Iv)

	// Decrypt the message, clear out the crypto headers and return
	stream.XORKeyStream(m.Data, m.Data)
	m.Head.Key = nil
	m.Head.Iv = nil
	return nil
}