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