nacl/sign: add package

This change adds the equivalents of crypto_sign, crypto_sign_open and
crypto_sign_keypair in TweetNaCl and libsodium using the Ed25519 system.
The original NaCl codebase does not contain functions with identical
semantics but its documentation stated the intent of using Ed25519 in
future releases.

Fixes golang/go#24350

Change-Id: I4c3c86b4875f2f718ad9299c2274b4ad9e11fbeb
Reviewed-on: https://go-review.googlesource.com/100578
Run-TryBot: Adam Langley <agl@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Adam Langley <agl@golang.org>
diff --git a/nacl/sign/sign.go b/nacl/sign/sign.go
new file mode 100644
index 0000000..a9ac0a7
--- /dev/null
+++ b/nacl/sign/sign.go
@@ -0,0 +1,83 @@
+// Copyright 2018 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 sign signs small messages using public-key cryptography.
+//
+// Sign uses Ed25519 to sign messages. The length of messages is not hidden.
+// 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 process
+// plaintext without verifying the signature. This is very dangerous, and this API
+// discourages it, but a protocol that uses excessive message sizes might present
+// some implementations with no other choice.
+// 3. 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.
+//
+// This package is not interoperable with the current release of NaCl
+// (https://nacl.cr.yp.to/sign.html), which does not support Ed25519 yet. However,
+// it is compatible with the NaCl fork libsodium (https://www.libsodium.org), as well
+// as TweetNaCl (https://tweetnacl.cr.yp.to/).
+package sign
+
+import (
+	"io"
+
+	"golang.org/x/crypto/ed25519"
+)
+
+// Overhead is the number of bytes of overhead when signing a message.
+const Overhead = 64
+
+// GenerateKey generates a new public/private key pair suitable for use with
+// Sign and Open.
+func GenerateKey(rand io.Reader) (publicKey *[32]byte, privateKey *[64]byte, err error) {
+	pub, priv, err := ed25519.GenerateKey(rand)
+	if err != nil {
+		return nil, nil, err
+	}
+	publicKey, privateKey = new([32]byte), new([64]byte)
+	copy((*publicKey)[:], pub)
+	copy((*privateKey)[:], priv)
+	return publicKey, privateKey, nil
+}
+
+// Sign appends a signed copy of message to out, which will be Overhead bytes
+// longer than the original and must not overlap it.
+func Sign(out, message []byte, privateKey *[64]byte) []byte {
+	sig := ed25519.Sign(ed25519.PrivateKey((*privateKey)[:]), message)
+	ret, out := sliceForAppend(out, Overhead+len(message))
+	copy(out, sig)
+	copy(out[Overhead:], message)
+	return ret
+}
+
+// Open verifies a signed message produced by Sign and appends the message to
+// out, which must not overlap the signed message. The output will be Overhead
+// bytes smaller than the signed message.
+func Open(out, signedMessage []byte, publicKey *[32]byte) ([]byte, bool) {
+	if len(signedMessage) < Overhead {
+		return nil, false
+	}
+	if !ed25519.Verify(ed25519.PublicKey((*publicKey)[:]), signedMessage[Overhead:], signedMessage[:Overhead]) {
+		return nil, false
+	}
+	ret, out := sliceForAppend(out, len(signedMessage)-Overhead)
+	copy(out, signedMessage[Overhead:])
+	return ret, true
+}
+
+// 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
+}
diff --git a/nacl/sign/sign_test.go b/nacl/sign/sign_test.go
new file mode 100644
index 0000000..0a6439a
--- /dev/null
+++ b/nacl/sign/sign_test.go
@@ -0,0 +1,74 @@
+// Copyright 2018 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 sign
+
+import (
+	"bytes"
+	"crypto/rand"
+	"encoding/hex"
+	"testing"
+)
+
+var testSignedMessage, _ = hex.DecodeString("26a0a47f733d02ddb74589b6cbd6f64a7dab1947db79395a1a9e00e4c902c0f185b119897b89b248d16bab4ea781b5a3798d25c2984aec833dddab57e0891e0d68656c6c6f20776f726c64")
+var testMessage = testSignedMessage[Overhead:]
+var testPublicKey [32]byte
+var testPrivateKey = [64]byte{
+	0x98, 0x3c, 0x6a, 0xa6, 0x21, 0xcc, 0xbb, 0xb2, 0xa7, 0xe8, 0x97, 0x94, 0xde, 0x5f, 0xf8, 0x11,
+	0x8a, 0xf3, 0x33, 0x1a, 0x03, 0x5c, 0x43, 0x99, 0x03, 0x13, 0x2d, 0xd7, 0xb4, 0xc4, 0x8b, 0xb0,
+	0xf6, 0x33, 0x20, 0xa3, 0x34, 0x8b, 0x7b, 0xe2, 0xfe, 0xb4, 0xe7, 0x3a, 0x54, 0x08, 0x2d, 0xd7,
+	0x0c, 0xb7, 0xc0, 0xe3, 0xbf, 0x62, 0x6c, 0x55, 0xf0, 0x33, 0x28, 0x52, 0xf8, 0x48, 0x7d, 0xfd,
+}
+
+func init() {
+	copy(testPublicKey[:], testPrivateKey[32:])
+}
+
+func TestSign(t *testing.T) {
+	signedMessage := Sign(nil, testMessage, &testPrivateKey)
+	if !bytes.Equal(signedMessage, testSignedMessage) {
+		t.Fatalf("signed message did not match, got\n%x\n, expected\n%x", signedMessage, testSignedMessage)
+	}
+}
+
+func TestOpen(t *testing.T) {
+	message, ok := Open(nil, testSignedMessage, &testPublicKey)
+	if !ok {
+		t.Fatalf("valid signed message not successfully verified")
+	}
+	if !bytes.Equal(message, testMessage) {
+		t.Fatalf("message did not match, got\n%x\n, expected\n%x", message, testMessage)
+	}
+	message, ok = Open(nil, testSignedMessage[1:], &testPublicKey)
+	if ok {
+		t.Fatalf("invalid signed message successfully verified")
+	}
+
+	badMessage := make([]byte, len(testSignedMessage))
+	copy(badMessage, testSignedMessage)
+	badMessage[5] ^= 1
+	if _, ok := Open(nil, badMessage, &testPublicKey); ok {
+		t.Fatalf("Open succeeded with a corrupt message")
+	}
+
+	var badPublicKey [32]byte
+	copy(badPublicKey[:], testPublicKey[:])
+	badPublicKey[5] ^= 1
+	if _, ok := Open(nil, testSignedMessage, &badPublicKey); ok {
+		t.Fatalf("Open succeeded with a corrupt public key")
+	}
+}
+
+func TestGenerateSignOpen(t *testing.T) {
+	publicKey, privateKey, _ := GenerateKey(rand.Reader)
+	signedMessage := Sign(nil, testMessage, privateKey)
+	message, ok := Open(nil, signedMessage, publicKey)
+	if !ok {
+		t.Fatalf("failed to verify signed message")
+	}
+
+	if !bytes.Equal(message, testMessage) {
+		t.Fatalf("verified message does not match signed messge, got\n%x\n, expected\n%x", message, testMessage)
+	}
+}