github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/crypto/ed25519/ed25519.go (about)

     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  	return bytes.Clone(priv[:SeedSize])
    76  }
    77  
    78  // Sign signs the given message with priv. rand is ignored.
    79  //
    80  // If opts.HashFunc() is [crypto.SHA512], the pre-hashed variant Ed25519ph is used
    81  // and message is expected to be a SHA-512 hash, otherwise opts.HashFunc() must
    82  // be [crypto.Hash](0) and the message must not be hashed, as Ed25519 performs two
    83  // passes over messages to be signed.
    84  //
    85  // A value of type [Options] can be used as opts, or crypto.Hash(0) or
    86  // crypto.SHA512 directly to select plain Ed25519 or Ed25519ph, respectively.
    87  func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) {
    88  	hash := opts.HashFunc()
    89  	context := ""
    90  	if opts, ok := opts.(*Options); ok {
    91  		context = opts.Context
    92  	}
    93  	switch {
    94  	case hash == crypto.SHA512: // Ed25519ph
    95  		if l := len(message); l != sha512.Size {
    96  			return nil, errors.New("ed25519: bad Ed25519ph message hash length: " + strconv.Itoa(l))
    97  		}
    98  		if l := len(context); l > 255 {
    99  			return nil, errors.New("ed25519: bad Ed25519ph context length: " + strconv.Itoa(l))
   100  		}
   101  		signature := make([]byte, SignatureSize)
   102  		sign(signature, priv, message, domPrefixPh, context)
   103  		return signature, nil
   104  	case hash == crypto.Hash(0) && context != "": // Ed25519ctx
   105  		if l := len(context); l > 255 {
   106  			return nil, errors.New("ed25519: bad Ed25519ctx context length: " + strconv.Itoa(l))
   107  		}
   108  		signature := make([]byte, SignatureSize)
   109  		sign(signature, priv, message, domPrefixCtx, context)
   110  		return signature, nil
   111  	case hash == crypto.Hash(0): // Ed25519
   112  		return Sign(priv, message), nil
   113  	default:
   114  		return nil, errors.New("ed25519: expected opts.HashFunc() zero (unhashed message, for standard Ed25519) or SHA-512 (for Ed25519ph)")
   115  	}
   116  }
   117  
   118  // Options can be used with [PrivateKey.Sign] or [VerifyWithOptions]
   119  // to select Ed25519 variants.
   120  type Options struct {
   121  	// Hash can be zero for regular Ed25519, or crypto.SHA512 for Ed25519ph.
   122  	Hash crypto.Hash
   123  
   124  	// Context, if not empty, selects Ed25519ctx or provides the context string
   125  	// for Ed25519ph. It can be at most 255 bytes in length.
   126  	Context string
   127  }
   128  
   129  // HashFunc returns o.Hash.
   130  func (o *Options) HashFunc() crypto.Hash { return o.Hash }
   131  
   132  // GenerateKey generates a public/private key pair using entropy from rand.
   133  // If rand is nil, [crypto/rand.Reader] will be used.
   134  func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) {
   135  	if rand == nil {
   136  		rand = cryptorand.Reader
   137  	}
   138  
   139  	seed := make([]byte, SeedSize)
   140  	if _, err := io.ReadFull(rand, seed); err != nil {
   141  		return nil, nil, err
   142  	}
   143  
   144  	privateKey := NewKeyFromSeed(seed)
   145  	publicKey := make([]byte, PublicKeySize)
   146  	copy(publicKey, privateKey[32:])
   147  
   148  	return publicKey, privateKey, nil
   149  }
   150  
   151  // NewKeyFromSeed calculates a private key from a seed. It will panic if
   152  // len(seed) is not [SeedSize]. This function is provided for interoperability
   153  // with RFC 8032. RFC 8032's private keys correspond to seeds in this
   154  // package.
   155  func NewKeyFromSeed(seed []byte) PrivateKey {
   156  	// Outline the function body so that the returned key can be stack-allocated.
   157  	privateKey := make([]byte, PrivateKeySize)
   158  	newKeyFromSeed(privateKey, seed)
   159  	return privateKey
   160  }
   161  
   162  func newKeyFromSeed(privateKey, seed []byte) {
   163  	if l := len(seed); l != SeedSize {
   164  		panic("ed25519: bad seed length: " + strconv.Itoa(l))
   165  	}
   166  
   167  	h := sha512.Sum512(seed)
   168  	s, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32])
   169  	if err != nil {
   170  		panic("ed25519: internal error: setting scalar failed")
   171  	}
   172  	A := (&edwards25519.Point{}).ScalarBaseMult(s)
   173  
   174  	publicKey := A.Bytes()
   175  
   176  	copy(privateKey, seed)
   177  	copy(privateKey[32:], publicKey)
   178  }
   179  
   180  // Sign signs the message with privateKey and returns a signature. It will
   181  // panic if len(privateKey) is not [PrivateKeySize].
   182  func Sign(privateKey PrivateKey, message []byte) []byte {
   183  	// Outline the function body so that the returned signature can be
   184  	// stack-allocated.
   185  	signature := make([]byte, SignatureSize)
   186  	sign(signature, privateKey, message, domPrefixPure, "")
   187  	return signature
   188  }
   189  
   190  // Domain separation prefixes used to disambiguate Ed25519/Ed25519ph/Ed25519ctx.
   191  // See RFC 8032, Section 2 and Section 5.1.
   192  const (
   193  	// domPrefixPure is empty for pure Ed25519.
   194  	domPrefixPure = ""
   195  	// domPrefixPh is dom2(phflag=1) for Ed25519ph. It must be followed by the
   196  	// uint8-length prefixed context.
   197  	domPrefixPh = "SigEd25519 no Ed25519 collisions\x01"
   198  	// domPrefixCtx is dom2(phflag=0) for Ed25519ctx. It must be followed by the
   199  	// uint8-length prefixed context.
   200  	domPrefixCtx = "SigEd25519 no Ed25519 collisions\x00"
   201  )
   202  
   203  func sign(signature, privateKey, message []byte, domPrefix, context string) {
   204  	if l := len(privateKey); l != PrivateKeySize {
   205  		panic("ed25519: bad private key length: " + strconv.Itoa(l))
   206  	}
   207  	seed, publicKey := privateKey[:SeedSize], privateKey[SeedSize:]
   208  
   209  	h := sha512.Sum512(seed)
   210  	s, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32])
   211  	if err != nil {
   212  		panic("ed25519: internal error: setting scalar failed")
   213  	}
   214  	prefix := h[32:]
   215  
   216  	mh := sha512.New()
   217  	if domPrefix != domPrefixPure {
   218  		mh.Write([]byte(domPrefix))
   219  		mh.Write([]byte{byte(len(context))})
   220  		mh.Write([]byte(context))
   221  	}
   222  	mh.Write(prefix)
   223  	mh.Write(message)
   224  	messageDigest := make([]byte, 0, sha512.Size)
   225  	messageDigest = mh.Sum(messageDigest)
   226  	r, err := edwards25519.NewScalar().SetUniformBytes(messageDigest)
   227  	if err != nil {
   228  		panic("ed25519: internal error: setting scalar failed")
   229  	}
   230  
   231  	R := (&edwards25519.Point{}).ScalarBaseMult(r)
   232  
   233  	kh := sha512.New()
   234  	if domPrefix != domPrefixPure {
   235  		kh.Write([]byte(domPrefix))
   236  		kh.Write([]byte{byte(len(context))})
   237  		kh.Write([]byte(context))
   238  	}
   239  	kh.Write(R.Bytes())
   240  	kh.Write(publicKey)
   241  	kh.Write(message)
   242  	hramDigest := make([]byte, 0, sha512.Size)
   243  	hramDigest = kh.Sum(hramDigest)
   244  	k, err := edwards25519.NewScalar().SetUniformBytes(hramDigest)
   245  	if err != nil {
   246  		panic("ed25519: internal error: setting scalar failed")
   247  	}
   248  
   249  	S := edwards25519.NewScalar().MultiplyAdd(k, s, r)
   250  
   251  	copy(signature[:32], R.Bytes())
   252  	copy(signature[32:], S.Bytes())
   253  }
   254  
   255  // Verify reports whether sig is a valid signature of message by publicKey. It
   256  // will panic if len(publicKey) is not [PublicKeySize].
   257  func Verify(publicKey PublicKey, message, sig []byte) bool {
   258  	return verify(publicKey, message, sig, domPrefixPure, "")
   259  }
   260  
   261  // VerifyWithOptions reports whether sig is a valid signature of message by
   262  // publicKey. A valid signature is indicated by returning a nil error. It will
   263  // panic if len(publicKey) is not [PublicKeySize].
   264  //
   265  // If opts.Hash is [crypto.SHA512], the pre-hashed variant Ed25519ph is used and
   266  // message is expected to be a SHA-512 hash, otherwise opts.Hash must be
   267  // [crypto.Hash](0) and the message must not be hashed, as Ed25519 performs two
   268  // passes over messages to be signed.
   269  func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error {
   270  	switch {
   271  	case opts.Hash == crypto.SHA512: // Ed25519ph
   272  		if l := len(message); l != sha512.Size {
   273  			return errors.New("ed25519: bad Ed25519ph message hash length: " + strconv.Itoa(l))
   274  		}
   275  		if l := len(opts.Context); l > 255 {
   276  			return errors.New("ed25519: bad Ed25519ph context length: " + strconv.Itoa(l))
   277  		}
   278  		if !verify(publicKey, message, sig, domPrefixPh, opts.Context) {
   279  			return errors.New("ed25519: invalid signature")
   280  		}
   281  		return nil
   282  	case opts.Hash == crypto.Hash(0) && opts.Context != "": // Ed25519ctx
   283  		if l := len(opts.Context); l > 255 {
   284  			return errors.New("ed25519: bad Ed25519ctx context length: " + strconv.Itoa(l))
   285  		}
   286  		if !verify(publicKey, message, sig, domPrefixCtx, opts.Context) {
   287  			return errors.New("ed25519: invalid signature")
   288  		}
   289  		return nil
   290  	case opts.Hash == crypto.Hash(0): // Ed25519
   291  		if !verify(publicKey, message, sig, domPrefixPure, "") {
   292  			return errors.New("ed25519: invalid signature")
   293  		}
   294  		return nil
   295  	default:
   296  		return errors.New("ed25519: expected opts.Hash zero (unhashed message, for standard Ed25519) or SHA-512 (for Ed25519ph)")
   297  	}
   298  }
   299  
   300  func verify(publicKey PublicKey, message, sig []byte, domPrefix, context string) bool {
   301  	if l := len(publicKey); l != PublicKeySize {
   302  		panic("ed25519: bad public key length: " + strconv.Itoa(l))
   303  	}
   304  
   305  	if len(sig) != SignatureSize || sig[63]&224 != 0 {
   306  		return false
   307  	}
   308  
   309  	A, err := (&edwards25519.Point{}).SetBytes(publicKey)
   310  	if err != nil {
   311  		return false
   312  	}
   313  
   314  	kh := sha512.New()
   315  	if domPrefix != domPrefixPure {
   316  		kh.Write([]byte(domPrefix))
   317  		kh.Write([]byte{byte(len(context))})
   318  		kh.Write([]byte(context))
   319  	}
   320  	kh.Write(sig[:32])
   321  	kh.Write(publicKey)
   322  	kh.Write(message)
   323  	hramDigest := make([]byte, 0, sha512.Size)
   324  	hramDigest = kh.Sum(hramDigest)
   325  	k, err := edwards25519.NewScalar().SetUniformBytes(hramDigest)
   326  	if err != nil {
   327  		panic("ed25519: internal error: setting scalar failed")
   328  	}
   329  
   330  	S, err := edwards25519.NewScalar().SetCanonicalBytes(sig[32:])
   331  	if err != nil {
   332  		return false
   333  	}
   334  
   335  	// [S]B = R + [k]A --> [k](-A) + [S]B = R
   336  	minusA := (&edwards25519.Point{}).Negate(A)
   337  	R := (&edwards25519.Point{}).VarTimeDoubleScalarBaseMult(k, minusA, S)
   338  
   339  	return bytes.Equal(sig[:32], R.Bytes())
   340  }