Implement RFC 7539 in Go.

In preparation for a Go implementation of the new TLS ciphers to test
against, implement the AEAD primitive.

Change-Id: I69b5b51257c3de16bdd36912ed2bc9d91ac853c8
Reviewed-on: https://boringssl-review.googlesource.com/6684
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/ssl/test/runner/chacha20_poly1305.go b/ssl/test/runner/chacha20_poly1305.go
index 4b49ff4..59c4dda 100644
--- a/ssl/test/runner/chacha20_poly1305.go
+++ b/ssl/test/runner/chacha20_poly1305.go
@@ -7,9 +7,7 @@
 	"errors"
 )
 
-// See draft-agl-tls-chacha20poly1305-04 and
-// draft-irtf-cfrg-chacha20-poly1305-10. Where the two differ, the
-// draft-agl-tls-chacha20poly1305-04 variant is implemented.
+// See RFC 7539.
 
 func leftRotate(a uint32, n uint) uint32 {
 	return (a << n) | (a >> (32 - n))
@@ -62,37 +60,30 @@
 	return
 }
 
-type chaCha20Poly1305Old struct {
-	key [32]byte
-}
-
-func newChaCha20Poly1305Old(key []byte) (cipher.AEAD, error) {
-	if len(key) != 32 {
-		return nil, errors.New("bad key length")
-	}
-	aead := new(chaCha20Poly1305Old)
-	copy(aead.key[:], key)
-	return aead, nil
-}
-
-func (c *chaCha20Poly1305Old) NonceSize() int { return 8 }
-func (c *chaCha20Poly1305Old) Overhead() int  { return 16 }
-
-func (c *chaCha20Poly1305Old) chaCha20(out, in, nonce []byte, counter uint64) {
+func chaCha20(out, in, key, nonce []byte, counter uint64) {
 	var state [16]uint32
 	state[0] = 0x61707865
 	state[1] = 0x3320646e
 	state[2] = 0x79622d32
 	state[3] = 0x6b206574
 	for i := 0; i < 8; i++ {
-		state[4+i] = binary.LittleEndian.Uint32(c.key[i*4 : i*4+4])
+		state[4+i] = binary.LittleEndian.Uint32(key[i*4 : i*4+4])
 	}
-	state[14] = binary.LittleEndian.Uint32(nonce[0:4])
-	state[15] = binary.LittleEndian.Uint32(nonce[4:8])
+
+	switch len(nonce) {
+	case 8:
+		state[14] = binary.LittleEndian.Uint32(nonce[0:4])
+		state[15] = binary.LittleEndian.Uint32(nonce[4:8])
+	case 12:
+		state[13] = binary.LittleEndian.Uint32(nonce[0:4])
+		state[14] = binary.LittleEndian.Uint32(nonce[4:8])
+		state[15] = binary.LittleEndian.Uint32(nonce[8:12])
+	default:
+		panic("bad nonce length")
+	}
 
 	for i := 0; i < len(in); i += 64 {
-		state[12] = uint32(counter & 0xffffffff)
-		state[13] = uint32(counter >> 32)
+		state[12] = uint32(counter)
 
 		var tmp [64]byte
 		chaCha20Block(&state, tmp[:])
@@ -108,7 +99,68 @@
 	}
 }
 
-func (c *chaCha20Poly1305Old) poly1305(tag *[16]byte, nonce, ciphertext, additionalData []byte) {
+// chaCha20Poly1305 implements the AEAD from
+// RFC 7539 and draft-agl-tls-chacha20poly1305-04.
+type chaCha20Poly1305 struct {
+	key [32]byte
+	// oldMode, if true, indicates that the draft spec should be
+	// implemented rather than the final, RFC version.
+	oldMode bool
+}
+
+func newChaCha20Poly1305(key []byte) (cipher.AEAD, error) {
+	if len(key) != 32 {
+		return nil, errors.New("bad key length")
+	}
+	aead := new(chaCha20Poly1305)
+	copy(aead.key[:], key)
+	return aead, nil
+}
+
+func newChaCha20Poly1305Old(key []byte) (cipher.AEAD, error) {
+	if len(key) != 32 {
+		return nil, errors.New("bad key length")
+	}
+	aead := &chaCha20Poly1305{
+		oldMode: true,
+	}
+	copy(aead.key[:], key)
+	return aead, nil
+}
+
+func (c *chaCha20Poly1305) NonceSize() int {
+	if c.oldMode {
+		return 8
+	} else {
+		return 12
+	}
+}
+
+func (c *chaCha20Poly1305) Overhead() int { return 16 }
+
+func (c *chaCha20Poly1305) poly1305(tag *[16]byte, nonce, ciphertext, additionalData []byte) {
+	input := make([]byte, 0, len(additionalData)+15+len(ciphertext)+15+8+8)
+	input = append(input, additionalData...)
+	var zeros [15]byte
+	if pad := len(input) % 16; pad != 0 {
+		input = append(input, zeros[:16-pad]...)
+	}
+	input = append(input, ciphertext...)
+	if pad := len(input) % 16; pad != 0 {
+		input = append(input, zeros[:16-pad]...)
+	}
+	input, out := sliceForAppend(input, 8)
+	binary.LittleEndian.PutUint64(out, uint64(len(additionalData)))
+	input, out = sliceForAppend(input, 8)
+	binary.LittleEndian.PutUint64(out, uint64(len(ciphertext)))
+
+	var poly1305Key [32]byte
+	chaCha20(poly1305Key[:], poly1305Key[:], c.key[:], nonce, 0)
+
+	poly1305Sum(tag, input, &poly1305Key)
+}
+
+func (c *chaCha20Poly1305) poly1305Old(tag *[16]byte, nonce, ciphertext, additionalData []byte) {
 	input := make([]byte, 0, len(additionalData)+8+len(ciphertext)+8)
 	input = append(input, additionalData...)
 	input, out := sliceForAppend(input, 8)
@@ -118,28 +170,32 @@
 	binary.LittleEndian.PutUint64(out, uint64(len(ciphertext)))
 
 	var poly1305Key [32]byte
-	c.chaCha20(poly1305Key[:], poly1305Key[:], nonce, 0)
+	chaCha20(poly1305Key[:], poly1305Key[:], c.key[:], nonce, 0)
 
 	poly1305Sum(tag, input, &poly1305Key)
 }
 
-func (c *chaCha20Poly1305Old) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
-	if len(nonce) != 8 {
+func (c *chaCha20Poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
+	if len(nonce) != c.NonceSize() {
 		panic("Bad nonce length")
 	}
 
 	ret, out := sliceForAppend(dst, len(plaintext)+16)
-	c.chaCha20(out[:len(plaintext)], plaintext, nonce, 1)
+	chaCha20(out[:len(plaintext)], plaintext, c.key[:], nonce, 1)
 
 	var tag [16]byte
-	c.poly1305(&tag, nonce, out[:len(plaintext)], additionalData)
+	if c.oldMode {
+		c.poly1305Old(&tag, nonce, out[:len(plaintext)], additionalData)
+	} else {
+		c.poly1305(&tag, nonce, out[:len(plaintext)], additionalData)
+	}
 	copy(out[len(plaintext):], tag[:])
 
 	return ret
 }
 
-func (c *chaCha20Poly1305Old) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
-	if len(nonce) != 8 {
+func (c *chaCha20Poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
+	if len(nonce) != c.NonceSize() {
 		panic("Bad nonce length")
 	}
 	if len(ciphertext) < 16 {
@@ -148,12 +204,16 @@
 	plaintextLen := len(ciphertext) - 16
 
 	var tag [16]byte
-	c.poly1305(&tag, nonce, ciphertext[:plaintextLen], additionalData)
+	if c.oldMode {
+		c.poly1305Old(&tag, nonce, ciphertext[:plaintextLen], additionalData)
+	} else {
+		c.poly1305(&tag, nonce, ciphertext[:plaintextLen], additionalData)
+	}
 	if subtle.ConstantTimeCompare(tag[:], ciphertext[plaintextLen:]) != 1 {
 		return nil, errors.New("chacha20: message authentication failed")
 	}
 
 	ret, out := sliceForAppend(dst, plaintextLen)
-	c.chaCha20(out, ciphertext[:plaintextLen], nonce, 1)
+	chaCha20(out, ciphertext[:plaintextLen], c.key[:], nonce, 1)
 	return ret, nil
 }
diff --git a/ssl/test/runner/chacha20_poly1305_test.go b/ssl/test/runner/chacha20_poly1305_test.go
index 446e7cd..4d19b8c 100644
--- a/ssl/test/runner/chacha20_poly1305_test.go
+++ b/ssl/test/runner/chacha20_poly1305_test.go
@@ -6,7 +6,7 @@
 	"testing"
 )
 
-// See draft-irtf-cfrg-chacha20-poly1305-10, section 2.1.1.
+// See RFC 7539, section 2.1.1.
 func TestChaChaQuarterRound(t *testing.T) {
 	state := [16]uint32{0x11111111, 0x01020304, 0x9b8d6f43, 0x01234567}
 	chaChaQuarterRound(&state, 0, 1, 2, 3)
@@ -17,7 +17,7 @@
 	}
 }
 
-// See draft-irtf-cfrg-chacha20-poly1305-10, section 2.2.1.
+// See RFC 7539, section 2.2.1.
 func TestChaChaQuarterRoundState(t *testing.T) {
 	state := [16]uint32{
 		0x879531e0, 0xc5ecf37d, 0x516461b1, 0xc9a62f8a,
@@ -40,7 +40,7 @@
 	}
 }
 
-// See draft-irtf-cfrg-chacha20-poly1305-10, section 2.3.2.
+// See RFC 7539, section 2.3.2.
 func TestChaCha20Block(t *testing.T) {
 	state := [16]uint32{
 		0x61707865, 0x3320646e, 0x79622d32, 0x6b206574,
@@ -66,13 +66,21 @@
 	}
 }
 
+func decodeHexOrPanic(in string) []byte {
+	out, err := hex.DecodeString(in)
+	if err != nil {
+		panic(err)
+	}
+	return out
+}
+
 // See draft-agl-tls-chacha20poly1305-04, section 7.
 func TestChaCha20Poly1305Old(t *testing.T) {
-	key, _ := hex.DecodeString("4290bcb154173531f314af57f3be3b5006da371ece272afa1b5dbdd1100a1007")
-	input, _ := hex.DecodeString("86d09974840bded2a5ca")
-	nonce, _ := hex.DecodeString("cd7cf67be39c794a")
-	ad, _ := hex.DecodeString("87e229d4500845a079c0")
-	output, _ := hex.DecodeString("e3e446f7ede9a19b62a4677dabf4e3d24b876bb284753896e1d6")
+	key := decodeHexOrPanic("4290bcb154173531f314af57f3be3b5006da371ece272afa1b5dbdd1100a1007")
+	input := decodeHexOrPanic("86d09974840bded2a5ca")
+	nonce := decodeHexOrPanic("cd7cf67be39c794a")
+	ad := decodeHexOrPanic("87e229d4500845a079c0")
+	output := decodeHexOrPanic("e3e446f7ede9a19b62a4677dabf4e3d24b876bb284753896e1d6")
 
 	aead, err := newChaCha20Poly1305Old(key)
 	if err != nil {
@@ -97,3 +105,58 @@
 		t.Errorf("Open on malformed data unexpectedly succeeded")
 	}
 }
+
+var chaCha20Poly1305TestVectors = []struct {
+	key, input, nonce, ad, output string
+}{
+	{
+		// See RFC 7539, section 2.8.2.
+		key:    "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
+		input:  "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e",
+		nonce:  "070000004041424344454647",
+		ad:     "50515253c0c1c2c3c4c5c6c7",
+		output: "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd0600691",
+	},
+	{
+		// See RFC 7539, section A.5.
+		key:    "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",
+		input:  "496e7465726e65742d4472616674732061726520647261667420646f63756d656e74732076616c696420666f722061206d6178696d756d206f6620736978206d6f6e74687320616e64206d617920626520757064617465642c207265706c616365642c206f72206f62736f6c65746564206279206f7468657220646f63756d656e747320617420616e792074696d652e20497420697320696e617070726f70726961746520746f2075736520496e7465726e65742d447261667473206173207265666572656e6365206d6174657269616c206f7220746f2063697465207468656d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67726573732e2fe2809d",
+		nonce:  "000000000102030405060708",
+		ad:     "f33388860000000000004e91",
+		output: "64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb24c6cfc18755d43eea09ee94e382d26b0bdb7b73c321b0100d4f03b7f355894cf332f830e710b97ce98c8a84abd0b948114ad176e008d33bd60f982b1ff37c8559797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c867e4b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523eaf4534d7f83fa1155b0047718cbc546a0d072b04b3564eea1b422273f548271a0bb2316053fa76991955ebd63159434ecebb4e466dae5a1073a6727627097a1049e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d6c6f2c29a6ad5cb4022b02709beead9d67890cbb22392336fea1851f38",
+	},
+}
+
+// See draft-agl-tls-chacha20poly1305-04, section 7.
+func TestChaCha20Poly1305(t *testing.T) {
+	for i, tt := range chaCha20Poly1305TestVectors {
+		key := decodeHexOrPanic(tt.key)
+		input := decodeHexOrPanic(tt.input)
+		nonce := decodeHexOrPanic(tt.nonce)
+		ad := decodeHexOrPanic(tt.ad)
+		output := decodeHexOrPanic(tt.output)
+
+		aead, err := newChaCha20Poly1305(key)
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		out, err := aead.Open(nil, nonce, output, ad)
+		if err != nil {
+			t.Errorf("%d. Open failed: %s", i, err)
+		} else if !bytes.Equal(out, input) {
+			t.Errorf("%d. Open gave %x, wanted %x", i, out, input)
+		}
+
+		out = aead.Seal(nil, nonce, input, ad)
+		if !bytes.Equal(out, output) {
+			t.Errorf("%d. Open gave %x, wanted %x", i, out, output)
+		}
+
+		out[0]++
+		_, err = aead.Open(nil, nonce, out, ad)
+		if err == nil {
+			t.Errorf("%d. Open on malformed data unexpectedly succeeded", i)
+		}
+	}
+}