// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package secretbox encrypts and authenticates small messages.

Secretbox uses XSalsa20 and Poly1305 to encrypt and authenticate messages with
secret-key cryptography. The length of messages is not hidden.

It is the caller's responsibility to ensure the uniqueness of noncesâ€”for
example, by using nonce 1 for the first message, nonce 2 for the second
message, etc. Nonces are long enough that randomly generated nonces have
negligible risk of collision.

Messages should be small because:

1. The whole message needs to be held in memory to be processed.

2. Using large messages pressures implementations on small machines to decrypt
and process plaintext before authenticating it. This is very dangerous, and
this API does not allow it, but a protocol that uses excessive message sizes
might present some implementations with no other choice.

3. Fixed overheads will be sufficiently amortised by messages as small as 8KB.

4. Performance may be improved by working with messages that fit into data caches.

Thus large amounts of data should be chunked so that each message is small.
(Each message still needs a unique nonce.) If in doubt, 16KB is a reasonable
chunk size.

This package is interoperable with NaCl: https://nacl.cr.yp.to/secretbox.html.
*/
package secretbox // import "github.com/kevinburke/nacl/secretbox"

import (
	"errors"

	"github.com/kevinburke/nacl"
	"github.com/kevinburke/nacl/internal/subtle"
	"github.com/kevinburke/nacl/onetimeauth"
	"golang.org/x/crypto/salsa20/salsa"
)

// Overhead is the number of bytes of overhead when boxing a message.
const Overhead = onetimeauth.Size

// sliceForAppend takes a slice and a requested number of bytes. It returns a
// slice with the contents of the given slice followed by that many bytes and a
// second slice that aliases into it and contains only the extra bytes. If the
// original slice has sufficient capacity then no allocation is performed.
func sliceForAppend(in []byte, n int) (head, tail []byte) {
	if total := len(in) + n; cap(in) >= total {
		head = in[:total]
	} else {
		head = make([]byte, total)
		copy(head, in)
	}
	tail = head[len(in):]
	return
}

// EasySeal encrypts message using key. A 24-byte nonce is generated and
// prepended to the output. The key and nonce pair must be unique for each
// distinct message, and the output will be Overhead+24 bytes longer than
// message.
func EasySeal(message []byte, key nacl.Key) []byte {
	nonce := nacl.NewNonce()
	return Seal(nonce[:], message, nonce, key)
}

// Seal appends an encrypted and authenticated copy of message to out, which
// must not overlap message. The key and nonce pair must be unique for each
// distinct message and the output will be Overhead bytes longer than message.
func Seal(out, message []byte, nonce nacl.Nonce, key nacl.Key) []byte {
	subKey, counter := nacl.Setup(nonce, key)

	// The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
	// Salsa20 works with 64-byte blocks, we also generate 32 bytes of
	// keystream as a side effect.
	var firstBlock [64]byte
	salsa.XORKeyStream(firstBlock[:], firstBlock[:], counter, subKey)

	var poly1305Key [32]byte
	copy(poly1305Key[:], firstBlock[:])

	ret, out := sliceForAppend(out, len(message)+onetimeauth.Size)
	if subtle.AnyOverlap(out, message) {
		panic("nacl: invalid buffer overlap")
	}

	// We XOR up to 32 bytes of message with the keystream generated from
	// the first block.
	firstMessageBlock := message
	if len(firstMessageBlock) > 32 {
		firstMessageBlock = firstMessageBlock[:32]
	}

	tagOut := out
	out = out[onetimeauth.Size:]
	for i, x := range firstMessageBlock {
		out[i] = firstBlock[32+i] ^ x
	}
	message = message[len(firstMessageBlock):]
	ciphertext := out
	out = out[len(firstMessageBlock):]

	// Now encrypt the rest.
	counter[8] = 1
	salsa.XORKeyStream(out, message, counter, subKey)

	tag := onetimeauth.Sum(ciphertext, &poly1305Key)
	copy(tagOut, tag[:])

	return ret
}

var errInvalidInput = errors.New("secretbox: Could not decrypt invalid input")

// EasyOpen decrypts box using key. We assume a 24-byte nonce is prepended to
// the encrypted text in box. The key and nonce pair must be unique for each
// distinct message.
func EasyOpen(box []byte, key nacl.Key) ([]byte, error) {
	if len(box) < 24 {
		return nil, errors.New("secretbox: message too short")
	}
	decryptNonce := new([24]byte)
	copy(decryptNonce[:], box[:24])
	decrypted, ok := Open([]byte{}, box[24:], decryptNonce, key)
	if !ok {
		return nil, errInvalidInput
	}
	return decrypted, nil
}

// Open authenticates and decrypts a box produced by Seal and appends the
// message to out, which must not overlap box. The output will be Overhead
// bytes smaller than box.
func Open(out, box []byte, nonce nacl.Nonce, key nacl.Key) ([]byte, bool) {
	if len(box) < Overhead {
		return nil, false
	}

	subKey, counter := nacl.Setup(nonce, key)

	// The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
	// Salsa20 works with 64-byte blocks, we also generate 32 bytes of
	// keystream as a side effect.
	var firstBlock [64]byte
	salsa.XORKeyStream(firstBlock[:], firstBlock[:], counter, subKey)

	var poly1305Key [32]byte
	copy(poly1305Key[:], firstBlock[:])
	var tag [onetimeauth.Size]byte
	copy(tag[:], box)

	if !onetimeauth.Verify(&tag, box[onetimeauth.Size:], &poly1305Key) {
		return nil, false
	}

	ret, out := sliceForAppend(out, len(box)-Overhead)

	// We XOR up to 32 bytes of box with the keystream generated from
	// the first block.
	box = box[Overhead:]
	firstMessageBlock := box
	if len(firstMessageBlock) > 32 {
		firstMessageBlock = firstMessageBlock[:32]
	}
	for i, x := range firstMessageBlock {
		out[i] = firstBlock[32+i] ^ x
	}

	box = box[len(firstMessageBlock):]
	out = out[len(firstMessageBlock):]

	// Now decrypt the rest.
	counter[8] = 1
	salsa.XORKeyStream(out, box, counter, subKey)

	return ret, true
}
