1// Copyright 2016 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package ed25519 implements the Ed25519 signature algorithm. See
6// https://ed25519.cr.yp.to/.
7//
8// These functions are also compatible with the “Ed25519” function defined in
9// RFC 8032. However, unlike RFC 8032's formulation, this package's private key
10// representation includes a public key suffix to make multiple signing
11// operations with the same key more efficient. This package refers to the RFC
12// 8032 private key as the “seed”.
13package ed25519
14
15import (
16	"bytes"
17	"crypto"
18	"crypto/ed25519/internal/edwards25519"
19	cryptorand "crypto/rand"
20	"crypto/sha512"
21	"errors"
22	"io"
23	"strconv"
24)
25
26const (
27	// PublicKeySize is the size, in bytes, of public keys as used in this package.
28	PublicKeySize = 32
29	// PrivateKeySize is the size, in bytes, of private keys as used in this package.
30	PrivateKeySize = 64
31	// SignatureSize is the size, in bytes, of signatures generated and verified by this package.
32	SignatureSize = 64
33	// SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
34	SeedSize = 32
35)
36
37// PublicKey is the type of Ed25519 public keys.
38type PublicKey []byte
39
40// Any methods implemented on PublicKey might need to also be implemented on
41// PrivateKey, as the latter embeds the former and will expose its methods.
42
43// Equal reports whether pub and x have the same value.
44func (pub PublicKey) Equal(x crypto.PublicKey) bool {
45	xx, ok := x.(PublicKey)
46	if !ok {
47		return false
48	}
49	return bytes.Equal(pub, xx)
50}
51
52// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.
53type PrivateKey []byte
54
55// Public returns the PublicKey corresponding to priv.
56func (priv PrivateKey) Public() crypto.PublicKey {
57	publicKey := make([]byte, PublicKeySize)
58	copy(publicKey, priv[32:])
59	return PublicKey(publicKey)
60}
61
62// Equal reports whether priv and x have the same value.
63func (priv PrivateKey) Equal(x crypto.PrivateKey) bool {
64	xx, ok := x.(PrivateKey)
65	if !ok {
66		return false
67	}
68	return bytes.Equal(priv, xx)
69}
70
71// Seed returns the private key seed corresponding to priv. It is provided for
72// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds
73// in this package.
74func (priv PrivateKey) Seed() []byte {
75	seed := make([]byte, SeedSize)
76	copy(seed, priv[:32])
77	return seed
78}
79
80// Sign signs the given message with priv.
81// Ed25519 performs two passes over messages to be signed and therefore cannot
82// handle pre-hashed messages. Thus opts.HashFunc() must return zero to
83// indicate the message hasn't been hashed. This can be achieved by passing
84// crypto.Hash(0) as the value for opts.
85func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) {
86	if opts.HashFunc() != crypto.Hash(0) {
87		return nil, errors.New("ed25519: cannot sign hashed message")
88	}
89
90	return Sign(priv, message), nil
91}
92
93// GenerateKey generates a public/private key pair using entropy from rand.
94// If rand is nil, crypto/rand.Reader will be used.
95func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) {
96	if rand == nil {
97		rand = cryptorand.Reader
98	}
99
100	seed := make([]byte, SeedSize)
101	if _, err := io.ReadFull(rand, seed); err != nil {
102		return nil, nil, err
103	}
104
105	privateKey := NewKeyFromSeed(seed)
106	publicKey := make([]byte, PublicKeySize)
107	copy(publicKey, privateKey[32:])
108
109	return publicKey, privateKey, nil
110}
111
112// NewKeyFromSeed calculates a private key from a seed. It will panic if
113// len(seed) is not SeedSize. This function is provided for interoperability
114// with RFC 8032. RFC 8032's private keys correspond to seeds in this
115// package.
116func NewKeyFromSeed(seed []byte) PrivateKey {
117	// Outline the function body so that the returned key can be stack-allocated.
118	privateKey := make([]byte, PrivateKeySize)
119	newKeyFromSeed(privateKey, seed)
120	return privateKey
121}
122
123func newKeyFromSeed(privateKey, seed []byte) {
124	if l := len(seed); l != SeedSize {
125		panic("ed25519: bad seed length: " + strconv.Itoa(l))
126	}
127
128	h := sha512.Sum512(seed)
129	s := edwards25519.NewScalar().SetBytesWithClamping(h[:32])
130	A := (&edwards25519.Point{}).ScalarBaseMult(s)
131
132	publicKey := A.Bytes()
133
134	copy(privateKey, seed)
135	copy(privateKey[32:], publicKey)
136}
137
138// Sign signs the message with privateKey and returns a signature. It will
139// panic if len(privateKey) is not PrivateKeySize.
140func Sign(privateKey PrivateKey, message []byte) []byte {
141	// Outline the function body so that the returned signature can be
142	// stack-allocated.
143	signature := make([]byte, SignatureSize)
144	sign(signature, privateKey, message)
145	return signature
146}
147
148func sign(signature, privateKey, message []byte) {
149	if l := len(privateKey); l != PrivateKeySize {
150		panic("ed25519: bad private key length: " + strconv.Itoa(l))
151	}
152	seed, publicKey := privateKey[:SeedSize], privateKey[SeedSize:]
153
154	h := sha512.Sum512(seed)
155	s := edwards25519.NewScalar().SetBytesWithClamping(h[:32])
156	prefix := h[32:]
157
158	mh := sha512.New()
159	mh.Write(prefix)
160	mh.Write(message)
161	messageDigest := make([]byte, 0, sha512.Size)
162	messageDigest = mh.Sum(messageDigest)
163	r := edwards25519.NewScalar().SetUniformBytes(messageDigest)
164
165	R := (&edwards25519.Point{}).ScalarBaseMult(r)
166
167	kh := sha512.New()
168	kh.Write(R.Bytes())
169	kh.Write(publicKey)
170	kh.Write(message)
171	hramDigest := make([]byte, 0, sha512.Size)
172	hramDigest = kh.Sum(hramDigest)
173	k := edwards25519.NewScalar().SetUniformBytes(hramDigest)
174
175	S := edwards25519.NewScalar().MultiplyAdd(k, s, r)
176
177	copy(signature[:32], R.Bytes())
178	copy(signature[32:], S.Bytes())
179}
180
181// Verify reports whether sig is a valid signature of message by publicKey. It
182// will panic if len(publicKey) is not PublicKeySize.
183func Verify(publicKey PublicKey, message, sig []byte) bool {
184	if l := len(publicKey); l != PublicKeySize {
185		panic("ed25519: bad public key length: " + strconv.Itoa(l))
186	}
187
188	if len(sig) != SignatureSize || sig[63]&224 != 0 {
189		return false
190	}
191
192	A, err := (&edwards25519.Point{}).SetBytes(publicKey)
193	if err != nil {
194		return false
195	}
196
197	kh := sha512.New()
198	kh.Write(sig[:32])
199	kh.Write(publicKey)
200	kh.Write(message)
201	hramDigest := make([]byte, 0, sha512.Size)
202	hramDigest = kh.Sum(hramDigest)
203	k := edwards25519.NewScalar().SetUniformBytes(hramDigest)
204
205	S, err := edwards25519.NewScalar().SetCanonicalBytes(sig[32:])
206	if err != nil {
207		return false
208	}
209
210	// [S]B = R + [k]A --> [k](-A) + [S]B = R
211	minusA := (&edwards25519.Point{}).Negate(A)
212	R := (&edwards25519.Point{}).VarTimeDoubleScalarBaseMult(k, minusA, S)
213
214	return bytes.Equal(sig[:32], R.Bytes())
215}
216