Source file src/crypto/ed25519/ed25519.go

     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”.
    13  package ed25519
    14  
    15  import (
    16  	"bytes"
    17  	"crypto"
    18  	"crypto/internal/edwards25519"
    19  	cryptorand "crypto/rand"
    20  	"crypto/sha512"
    21  	"errors"
    22  	"io"
    23  	"strconv"
    24  )
    25  
    26  const (
    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.
    38  type 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.
    44  func (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.
    53  type PrivateKey []byte
    54  
    55  // Public returns the PublicKey corresponding to priv.
    56  func (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.
    63  func (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.
    74  func (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.
    85  func (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.
    95  func 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.
   116  func 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  
   123  func 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, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32])
   130  	if err != nil {
   131  		panic("ed25519: internal error: setting scalar failed")
   132  	}
   133  	A := (&edwards25519.Point{}).ScalarBaseMult(s)
   134  
   135  	publicKey := A.Bytes()
   136  
   137  	copy(privateKey, seed)
   138  	copy(privateKey[32:], publicKey)
   139  }
   140  
   141  // Sign signs the message with privateKey and returns a signature. It will
   142  // panic if len(privateKey) is not PrivateKeySize.
   143  func Sign(privateKey PrivateKey, message []byte) []byte {
   144  	// Outline the function body so that the returned signature can be
   145  	// stack-allocated.
   146  	signature := make([]byte, SignatureSize)
   147  	sign(signature, privateKey, message)
   148  	return signature
   149  }
   150  
   151  func sign(signature, privateKey, message []byte) {
   152  	if l := len(privateKey); l != PrivateKeySize {
   153  		panic("ed25519: bad private key length: " + strconv.Itoa(l))
   154  	}
   155  	seed, publicKey := privateKey[:SeedSize], privateKey[SeedSize:]
   156  
   157  	h := sha512.Sum512(seed)
   158  	s, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32])
   159  	if err != nil {
   160  		panic("ed25519: internal error: setting scalar failed")
   161  	}
   162  	prefix := h[32:]
   163  
   164  	mh := sha512.New()
   165  	mh.Write(prefix)
   166  	mh.Write(message)
   167  	messageDigest := make([]byte, 0, sha512.Size)
   168  	messageDigest = mh.Sum(messageDigest)
   169  	r, err := edwards25519.NewScalar().SetUniformBytes(messageDigest)
   170  	if err != nil {
   171  		panic("ed25519: internal error: setting scalar failed")
   172  	}
   173  
   174  	R := (&edwards25519.Point{}).ScalarBaseMult(r)
   175  
   176  	kh := sha512.New()
   177  	kh.Write(R.Bytes())
   178  	kh.Write(publicKey)
   179  	kh.Write(message)
   180  	hramDigest := make([]byte, 0, sha512.Size)
   181  	hramDigest = kh.Sum(hramDigest)
   182  	k, err := edwards25519.NewScalar().SetUniformBytes(hramDigest)
   183  	if err != nil {
   184  		panic("ed25519: internal error: setting scalar failed")
   185  	}
   186  
   187  	S := edwards25519.NewScalar().MultiplyAdd(k, s, r)
   188  
   189  	copy(signature[:32], R.Bytes())
   190  	copy(signature[32:], S.Bytes())
   191  }
   192  
   193  // Verify reports whether sig is a valid signature of message by publicKey. It
   194  // will panic if len(publicKey) is not PublicKeySize.
   195  func Verify(publicKey PublicKey, message, sig []byte) bool {
   196  	if l := len(publicKey); l != PublicKeySize {
   197  		panic("ed25519: bad public key length: " + strconv.Itoa(l))
   198  	}
   199  
   200  	if len(sig) != SignatureSize || sig[63]&224 != 0 {
   201  		return false
   202  	}
   203  
   204  	A, err := (&edwards25519.Point{}).SetBytes(publicKey)
   205  	if err != nil {
   206  		return false
   207  	}
   208  
   209  	kh := sha512.New()
   210  	kh.Write(sig[:32])
   211  	kh.Write(publicKey)
   212  	kh.Write(message)
   213  	hramDigest := make([]byte, 0, sha512.Size)
   214  	hramDigest = kh.Sum(hramDigest)
   215  	k, err := edwards25519.NewScalar().SetUniformBytes(hramDigest)
   216  	if err != nil {
   217  		panic("ed25519: internal error: setting scalar failed")
   218  	}
   219  
   220  	S, err := edwards25519.NewScalar().SetCanonicalBytes(sig[32:])
   221  	if err != nil {
   222  		return false
   223  	}
   224  
   225  	// [S]B = R + [k]A --> [k](-A) + [S]B = R
   226  	minusA := (&edwards25519.Point{}).Negate(A)
   227  	R := (&edwards25519.Point{}).VarTimeDoubleScalarBaseMult(k, minusA, S)
   228  
   229  	return bytes.Equal(sig[:32], R.Bytes())
   230  }
   231  

View as plain text