github.com/dorkamotorka/go/src@v0.0.0-20230614113921-187095f0e316/crypto/rsa/rsa.go (about)

     1  // Copyright 2009 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 rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.
     6  //
     7  // RSA is a single, fundamental operation that is used in this package to
     8  // implement either public-key encryption or public-key signatures.
     9  //
    10  // The original specification for encryption and signatures with RSA is PKCS #1
    11  // and the terms "RSA encryption" and "RSA signatures" by default refer to
    12  // PKCS #1 version 1.5. However, that specification has flaws and new designs
    13  // should use version 2, usually called by just OAEP and PSS, where
    14  // possible.
    15  //
    16  // Two sets of interfaces are included in this package. When a more abstract
    17  // interface isn't necessary, there are functions for encrypting/decrypting
    18  // with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract
    19  // over the public key primitive, the PrivateKey type implements the
    20  // Decrypter and Signer interfaces from the crypto package.
    21  //
    22  // Operations in this package are implemented using constant-time algorithms,
    23  // except for [GenerateKey], [PrivateKey.Precompute], and [PrivateKey.Validate].
    24  // Every other operation only leaks the bit size of the involved values, which
    25  // all depend on the selected key size.
    26  package rsa
    27  
    28  import (
    29  	"crypto"
    30  	"crypto/internal/bigmod"
    31  	"crypto/internal/boring"
    32  	"crypto/internal/boring/bbig"
    33  	"crypto/internal/randutil"
    34  	"crypto/rand"
    35  	"crypto/subtle"
    36  	"errors"
    37  	"hash"
    38  	"io"
    39  	"math"
    40  	"math/big"
    41  )
    42  
    43  var bigOne = big.NewInt(1)
    44  
    45  // A PublicKey represents the public part of an RSA key.
    46  type PublicKey struct {
    47  	N *big.Int // modulus
    48  	E int      // public exponent
    49  }
    50  
    51  // Any methods implemented on PublicKey might need to also be implemented on
    52  // PrivateKey, as the latter embeds the former and will expose its methods.
    53  
    54  // Size returns the modulus size in bytes. Raw signatures and ciphertexts
    55  // for or by this public key will have the same size.
    56  func (pub *PublicKey) Size() int {
    57  	return (pub.N.BitLen() + 7) / 8
    58  }
    59  
    60  // Equal reports whether pub and x have the same value.
    61  func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
    62  	xx, ok := x.(*PublicKey)
    63  	if !ok {
    64  		return false
    65  	}
    66  	return bigIntEqual(pub.N, xx.N) && pub.E == xx.E
    67  }
    68  
    69  // OAEPOptions is an interface for passing options to OAEP decryption using the
    70  // crypto.Decrypter interface.
    71  type OAEPOptions struct {
    72  	// Hash is the hash function that will be used when generating the mask.
    73  	Hash crypto.Hash
    74  
    75  	// MGFHash is the hash function used for MGF1.
    76  	// If zero, Hash is used instead.
    77  	MGFHash crypto.Hash
    78  
    79  	// Label is an arbitrary byte string that must be equal to the value
    80  	// used when encrypting.
    81  	Label []byte
    82  }
    83  
    84  var (
    85  	errPublicModulus       = errors.New("crypto/rsa: missing public modulus")
    86  	errPublicExponentSmall = errors.New("crypto/rsa: public exponent too small")
    87  	errPublicExponentLarge = errors.New("crypto/rsa: public exponent too large")
    88  )
    89  
    90  // checkPub sanity checks the public key before we use it.
    91  // We require pub.E to fit into a 32-bit integer so that we
    92  // do not have different behavior depending on whether
    93  // int is 32 or 64 bits. See also
    94  // https://www.imperialviolet.org/2012/03/16/rsae.html.
    95  func checkPub(pub *PublicKey) error {
    96  	if pub.N == nil {
    97  		return errPublicModulus
    98  	}
    99  	if pub.E < 2 {
   100  		return errPublicExponentSmall
   101  	}
   102  	if pub.E > 1<<31-1 {
   103  		return errPublicExponentLarge
   104  	}
   105  	return nil
   106  }
   107  
   108  // A PrivateKey represents an RSA key
   109  type PrivateKey struct {
   110  	PublicKey            // public part.
   111  	D         *big.Int   // private exponent
   112  	Primes    []*big.Int // prime factors of N, has >= 2 elements.
   113  
   114  	// Precomputed contains precomputed values that speed up RSA operations,
   115  	// if available. It must be generated by calling PrivateKey.Precompute and
   116  	// must not be modified.
   117  	Precomputed PrecomputedValues
   118  }
   119  
   120  // Public returns the public key corresponding to priv.
   121  func (priv *PrivateKey) Public() crypto.PublicKey {
   122  	return &priv.PublicKey
   123  }
   124  
   125  // Equal reports whether priv and x have equivalent values. It ignores
   126  // Precomputed values.
   127  func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {
   128  	xx, ok := x.(*PrivateKey)
   129  	if !ok {
   130  		return false
   131  	}
   132  	if !priv.PublicKey.Equal(&xx.PublicKey) || !bigIntEqual(priv.D, xx.D) {
   133  		return false
   134  	}
   135  	if len(priv.Primes) != len(xx.Primes) {
   136  		return false
   137  	}
   138  	for i := range priv.Primes {
   139  		if !bigIntEqual(priv.Primes[i], xx.Primes[i]) {
   140  			return false
   141  		}
   142  	}
   143  	return true
   144  }
   145  
   146  // bigIntEqual reports whether a and b are equal leaking only their bit length
   147  // through timing side-channels.
   148  func bigIntEqual(a, b *big.Int) bool {
   149  	return subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
   150  }
   151  
   152  // Sign signs digest with priv, reading randomness from rand. If opts is a
   153  // *PSSOptions then the PSS algorithm will be used, otherwise PKCS #1 v1.5 will
   154  // be used. digest must be the result of hashing the input message using
   155  // opts.HashFunc().
   156  //
   157  // This method implements crypto.Signer, which is an interface to support keys
   158  // where the private part is kept in, for example, a hardware module. Common
   159  // uses should use the Sign* functions in this package directly.
   160  func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
   161  	if pssOpts, ok := opts.(*PSSOptions); ok {
   162  		return SignPSS(rand, priv, pssOpts.Hash, digest, pssOpts)
   163  	}
   164  
   165  	return SignPKCS1v15(rand, priv, opts.HashFunc(), digest)
   166  }
   167  
   168  // Decrypt decrypts ciphertext with priv. If opts is nil or of type
   169  // *PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwise
   170  // opts must have type *OAEPOptions and OAEP decryption is done.
   171  func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
   172  	if opts == nil {
   173  		return DecryptPKCS1v15(rand, priv, ciphertext)
   174  	}
   175  
   176  	switch opts := opts.(type) {
   177  	case *OAEPOptions:
   178  		if opts.MGFHash == 0 {
   179  			return decryptOAEP(opts.Hash.New(), opts.Hash.New(), rand, priv, ciphertext, opts.Label)
   180  		} else {
   181  			return decryptOAEP(opts.Hash.New(), opts.MGFHash.New(), rand, priv, ciphertext, opts.Label)
   182  		}
   183  
   184  	case *PKCS1v15DecryptOptions:
   185  		if l := opts.SessionKeyLen; l > 0 {
   186  			plaintext = make([]byte, l)
   187  			if _, err := io.ReadFull(rand, plaintext); err != nil {
   188  				return nil, err
   189  			}
   190  			if err := DecryptPKCS1v15SessionKey(rand, priv, ciphertext, plaintext); err != nil {
   191  				return nil, err
   192  			}
   193  			return plaintext, nil
   194  		} else {
   195  			return DecryptPKCS1v15(rand, priv, ciphertext)
   196  		}
   197  
   198  	default:
   199  		return nil, errors.New("crypto/rsa: invalid options for Decrypt")
   200  	}
   201  }
   202  
   203  type PrecomputedValues struct {
   204  	Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
   205  	Qinv   *big.Int // Q^-1 mod P
   206  
   207  	// CRTValues is used for the 3rd and subsequent primes. Due to a
   208  	// historical accident, the CRT for the first two primes is handled
   209  	// differently in PKCS #1 and interoperability is sufficiently
   210  	// important that we mirror this.
   211  	//
   212  	// Deprecated: These values are still filled in by Precompute for
   213  	// backwards compatibility but are not used. Multi-prime RSA is very rare,
   214  	// and is implemented by this package without CRT optimizations to limit
   215  	// complexity.
   216  	CRTValues []CRTValue
   217  
   218  	n, p, q *bigmod.Modulus // moduli for CRT with Montgomery precomputed constants
   219  }
   220  
   221  // CRTValue contains the precomputed Chinese remainder theorem values.
   222  type CRTValue struct {
   223  	Exp   *big.Int // D mod (prime-1).
   224  	Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
   225  	R     *big.Int // product of primes prior to this (inc p and q).
   226  }
   227  
   228  // Validate performs basic sanity checks on the key.
   229  // It returns nil if the key is valid, or else an error describing a problem.
   230  func (priv *PrivateKey) Validate() error {
   231  	if err := checkPub(&priv.PublicKey); err != nil {
   232  		return err
   233  	}
   234  
   235  	// Check that Πprimes == n.
   236  	modulus := new(big.Int).Set(bigOne)
   237  	for _, prime := range priv.Primes {
   238  		// Any primes ≤ 1 will cause divide-by-zero panics later.
   239  		if prime.Cmp(bigOne) <= 0 {
   240  			return errors.New("crypto/rsa: invalid prime value")
   241  		}
   242  		modulus.Mul(modulus, prime)
   243  	}
   244  	if modulus.Cmp(priv.N) != 0 {
   245  		return errors.New("crypto/rsa: invalid modulus")
   246  	}
   247  
   248  	// Check that de ≡ 1 mod p-1, for each prime.
   249  	// This implies that e is coprime to each p-1 as e has a multiplicative
   250  	// inverse. Therefore e is coprime to lcm(p-1,q-1,r-1,...) =
   251  	// exponent(ℤ/nℤ). It also implies that a^de ≡ a mod p as a^(p-1) ≡ 1
   252  	// mod p. Thus a^de ≡ a mod n for all a coprime to n, as required.
   253  	congruence := new(big.Int)
   254  	de := new(big.Int).SetInt64(int64(priv.E))
   255  	de.Mul(de, priv.D)
   256  	for _, prime := range priv.Primes {
   257  		pminus1 := new(big.Int).Sub(prime, bigOne)
   258  		congruence.Mod(de, pminus1)
   259  		if congruence.Cmp(bigOne) != 0 {
   260  			return errors.New("crypto/rsa: invalid exponents")
   261  		}
   262  	}
   263  	return nil
   264  }
   265  
   266  // GenerateKey generates an RSA keypair of the given bit size using the
   267  // random source random (for example, crypto/rand.Reader).
   268  func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) {
   269  	return GenerateMultiPrimeKey(random, 2, bits)
   270  }
   271  
   272  // GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit
   273  // size and the given random source.
   274  //
   275  // Table 1 in "[On the Security of Multi-prime RSA]" suggests maximum numbers of
   276  // primes for a given bit size.
   277  //
   278  // Although the public keys are compatible (actually, indistinguishable) from
   279  // the 2-prime case, the private keys are not. Thus it may not be possible to
   280  // export multi-prime private keys in certain formats or to subsequently import
   281  // them into other code.
   282  //
   283  // This package does not implement CRT optimizations for multi-prime RSA, so the
   284  // keys with more than two primes will have worse performance.
   285  //
   286  // Deprecated: The use of this function with a number of primes different from
   287  // two is not recommended for the above security, compatibility, and performance
   288  // reasons. Use GenerateKey instead.
   289  //
   290  // [On the Security of Multi-prime RSA]: http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
   291  func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error) {
   292  	randutil.MaybeReadByte(random)
   293  
   294  	if boring.Enabled && random == boring.RandReader && nprimes == 2 &&
   295  		(bits == 2048 || bits == 3072 || bits == 4096) {
   296  		bN, bE, bD, bP, bQ, bDp, bDq, bQinv, err := boring.GenerateKeyRSA(bits)
   297  		if err != nil {
   298  			return nil, err
   299  		}
   300  		N := bbig.Dec(bN)
   301  		E := bbig.Dec(bE)
   302  		D := bbig.Dec(bD)
   303  		P := bbig.Dec(bP)
   304  		Q := bbig.Dec(bQ)
   305  		Dp := bbig.Dec(bDp)
   306  		Dq := bbig.Dec(bDq)
   307  		Qinv := bbig.Dec(bQinv)
   308  		e64 := E.Int64()
   309  		if !E.IsInt64() || int64(int(e64)) != e64 {
   310  			return nil, errors.New("crypto/rsa: generated key exponent too large")
   311  		}
   312  
   313  		mn, err := bigmod.NewModulusFromBig(N)
   314  		if err != nil {
   315  			return nil, err
   316  		}
   317  		mp, err := bigmod.NewModulusFromBig(P)
   318  		if err != nil {
   319  			return nil, err
   320  		}
   321  		mq, err := bigmod.NewModulusFromBig(Q)
   322  		if err != nil {
   323  			return nil, err
   324  		}
   325  
   326  		key := &PrivateKey{
   327  			PublicKey: PublicKey{
   328  				N: N,
   329  				E: int(e64),
   330  			},
   331  			D:      D,
   332  			Primes: []*big.Int{P, Q},
   333  			Precomputed: PrecomputedValues{
   334  				Dp:        Dp,
   335  				Dq:        Dq,
   336  				Qinv:      Qinv,
   337  				CRTValues: make([]CRTValue, 0), // non-nil, to match Precompute
   338  				n:         mn,
   339  				p:         mp,
   340  				q:         mq,
   341  			},
   342  		}
   343  		return key, nil
   344  	}
   345  
   346  	priv := new(PrivateKey)
   347  	priv.E = 65537
   348  
   349  	if nprimes < 2 {
   350  		return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
   351  	}
   352  
   353  	if bits < 64 {
   354  		primeLimit := float64(uint64(1) << uint(bits/nprimes))
   355  		// pi approximates the number of primes less than primeLimit
   356  		pi := primeLimit / (math.Log(primeLimit) - 1)
   357  		// Generated primes start with 11 (in binary) so we can only
   358  		// use a quarter of them.
   359  		pi /= 4
   360  		// Use a factor of two to ensure that key generation terminates
   361  		// in a reasonable amount of time.
   362  		pi /= 2
   363  		if pi <= float64(nprimes) {
   364  			return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key")
   365  		}
   366  	}
   367  
   368  	primes := make([]*big.Int, nprimes)
   369  
   370  NextSetOfPrimes:
   371  	for {
   372  		todo := bits
   373  		// crypto/rand should set the top two bits in each prime.
   374  		// Thus each prime has the form
   375  		//   p_i = 2^bitlen(p_i) × 0.11... (in base 2).
   376  		// And the product is:
   377  		//   P = 2^todo × α
   378  		// where α is the product of nprimes numbers of the form 0.11...
   379  		//
   380  		// If α < 1/2 (which can happen for nprimes > 2), we need to
   381  		// shift todo to compensate for lost bits: the mean value of 0.11...
   382  		// is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2
   383  		// will give good results.
   384  		if nprimes >= 7 {
   385  			todo += (nprimes - 2) / 5
   386  		}
   387  		for i := 0; i < nprimes; i++ {
   388  			var err error
   389  			primes[i], err = rand.Prime(random, todo/(nprimes-i))
   390  			if err != nil {
   391  				return nil, err
   392  			}
   393  			todo -= primes[i].BitLen()
   394  		}
   395  
   396  		// Make sure that primes is pairwise unequal.
   397  		for i, prime := range primes {
   398  			for j := 0; j < i; j++ {
   399  				if prime.Cmp(primes[j]) == 0 {
   400  					continue NextSetOfPrimes
   401  				}
   402  			}
   403  		}
   404  
   405  		n := new(big.Int).Set(bigOne)
   406  		totient := new(big.Int).Set(bigOne)
   407  		pminus1 := new(big.Int)
   408  		for _, prime := range primes {
   409  			n.Mul(n, prime)
   410  			pminus1.Sub(prime, bigOne)
   411  			totient.Mul(totient, pminus1)
   412  		}
   413  		if n.BitLen() != bits {
   414  			// This should never happen for nprimes == 2 because
   415  			// crypto/rand should set the top two bits in each prime.
   416  			// For nprimes > 2 we hope it does not happen often.
   417  			continue NextSetOfPrimes
   418  		}
   419  
   420  		priv.D = new(big.Int)
   421  		e := big.NewInt(int64(priv.E))
   422  		ok := priv.D.ModInverse(e, totient)
   423  
   424  		if ok != nil {
   425  			priv.Primes = primes
   426  			priv.N = n
   427  			break
   428  		}
   429  	}
   430  
   431  	priv.Precompute()
   432  	return priv, nil
   433  }
   434  
   435  // incCounter increments a four byte, big-endian counter.
   436  func incCounter(c *[4]byte) {
   437  	if c[3]++; c[3] != 0 {
   438  		return
   439  	}
   440  	if c[2]++; c[2] != 0 {
   441  		return
   442  	}
   443  	if c[1]++; c[1] != 0 {
   444  		return
   445  	}
   446  	c[0]++
   447  }
   448  
   449  // mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function
   450  // specified in PKCS #1 v2.1.
   451  func mgf1XOR(out []byte, hash hash.Hash, seed []byte) {
   452  	var counter [4]byte
   453  	var digest []byte
   454  
   455  	done := 0
   456  	for done < len(out) {
   457  		hash.Write(seed)
   458  		hash.Write(counter[0:4])
   459  		digest = hash.Sum(digest[:0])
   460  		hash.Reset()
   461  
   462  		for i := 0; i < len(digest) && done < len(out); i++ {
   463  			out[done] ^= digest[i]
   464  			done++
   465  		}
   466  		incCounter(&counter)
   467  	}
   468  }
   469  
   470  // ErrMessageTooLong is returned when attempting to encrypt or sign a message
   471  // which is too large for the size of the key. When using SignPSS, this can also
   472  // be returned if the size of the salt is too large.
   473  var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")
   474  
   475  func encrypt(pub *PublicKey, plaintext []byte) ([]byte, error) {
   476  	boring.Unreachable()
   477  
   478  	// Most of the CPU time for encryption and verification is spent in this
   479  	// NewModulusFromBig call, because PublicKey doesn't have a Precomputed
   480  	// field. If performance becomes an issue, consider placing a private
   481  	// sync.Once on PublicKey to compute this.
   482  	N, err := bigmod.NewModulusFromBig(pub.N)
   483  	if err != nil {
   484  		return nil, err
   485  	}
   486  	m, err := bigmod.NewNat().SetBytes(plaintext, N)
   487  	if err != nil {
   488  		return nil, err
   489  	}
   490  	e := uint(pub.E)
   491  
   492  	return bigmod.NewNat().ExpShort(m, e, N).Bytes(N), nil
   493  }
   494  
   495  // EncryptOAEP encrypts the given message with RSA-OAEP.
   496  //
   497  // OAEP is parameterised by a hash function that is used as a random oracle.
   498  // Encryption and decryption of a given message must use the same hash function
   499  // and sha256.New() is a reasonable choice.
   500  //
   501  // The random parameter is used as a source of entropy to ensure that
   502  // encrypting the same message twice doesn't result in the same ciphertext.
   503  //
   504  // The label parameter may contain arbitrary data that will not be encrypted,
   505  // but which gives important context to the message. For example, if a given
   506  // public key is used to encrypt two types of messages then distinct label
   507  // values could be used to ensure that a ciphertext for one purpose cannot be
   508  // used for another by an attacker. If not required it can be empty.
   509  //
   510  // The message must be no longer than the length of the public modulus minus
   511  // twice the hash length, minus a further 2.
   512  func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error) {
   513  	if err := checkPub(pub); err != nil {
   514  		return nil, err
   515  	}
   516  	hash.Reset()
   517  	k := pub.Size()
   518  	if len(msg) > k-2*hash.Size()-2 {
   519  		return nil, ErrMessageTooLong
   520  	}
   521  
   522  	if boring.Enabled && random == boring.RandReader {
   523  		bkey, err := boringPublicKey(pub)
   524  		if err != nil {
   525  			return nil, err
   526  		}
   527  		return boring.EncryptRSAOAEP(hash, hash, bkey, msg, label)
   528  	}
   529  	boring.UnreachableExceptTests()
   530  
   531  	hash.Write(label)
   532  	lHash := hash.Sum(nil)
   533  	hash.Reset()
   534  
   535  	em := make([]byte, k)
   536  	seed := em[1 : 1+hash.Size()]
   537  	db := em[1+hash.Size():]
   538  
   539  	copy(db[0:hash.Size()], lHash)
   540  	db[len(db)-len(msg)-1] = 1
   541  	copy(db[len(db)-len(msg):], msg)
   542  
   543  	_, err := io.ReadFull(random, seed)
   544  	if err != nil {
   545  		return nil, err
   546  	}
   547  
   548  	mgf1XOR(db, hash, seed)
   549  	mgf1XOR(seed, hash, db)
   550  
   551  	if boring.Enabled {
   552  		var bkey *boring.PublicKeyRSA
   553  		bkey, err = boringPublicKey(pub)
   554  		if err != nil {
   555  			return nil, err
   556  		}
   557  		return boring.EncryptRSANoPadding(bkey, em)
   558  	}
   559  
   560  	return encrypt(pub, em)
   561  }
   562  
   563  // ErrDecryption represents a failure to decrypt a message.
   564  // It is deliberately vague to avoid adaptive attacks.
   565  var ErrDecryption = errors.New("crypto/rsa: decryption error")
   566  
   567  // ErrVerification represents a failure to verify a signature.
   568  // It is deliberately vague to avoid adaptive attacks.
   569  var ErrVerification = errors.New("crypto/rsa: verification error")
   570  
   571  // Precompute performs some calculations that speed up private key operations
   572  // in the future.
   573  func (priv *PrivateKey) Precompute() {
   574  	if priv.Precomputed.n == nil && len(priv.Primes) == 2 {
   575  		// Precomputed values _should_ always be valid, but if they aren't
   576  		// just return. We could also panic.
   577  		var err error
   578  		priv.Precomputed.n, err = bigmod.NewModulusFromBig(priv.N)
   579  		if err != nil {
   580  			return
   581  		}
   582  		priv.Precomputed.p, err = bigmod.NewModulusFromBig(priv.Primes[0])
   583  		if err != nil {
   584  			// Unset previous values, so we either have everything or nothing
   585  			priv.Precomputed.n = nil
   586  			return
   587  		}
   588  		priv.Precomputed.q, err = bigmod.NewModulusFromBig(priv.Primes[1])
   589  		if err != nil {
   590  			// Unset previous values, so we either have everything or nothing
   591  			priv.Precomputed.n, priv.Precomputed.p = nil, nil
   592  			return
   593  		}
   594  	}
   595  
   596  	// Fill in the backwards-compatibility *big.Int values.
   597  	if priv.Precomputed.Dp != nil {
   598  		return
   599  	}
   600  
   601  	priv.Precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
   602  	priv.Precomputed.Dp.Mod(priv.D, priv.Precomputed.Dp)
   603  
   604  	priv.Precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
   605  	priv.Precomputed.Dq.Mod(priv.D, priv.Precomputed.Dq)
   606  
   607  	priv.Precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])
   608  
   609  	r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])
   610  	priv.Precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2)
   611  	for i := 2; i < len(priv.Primes); i++ {
   612  		prime := priv.Primes[i]
   613  		values := &priv.Precomputed.CRTValues[i-2]
   614  
   615  		values.Exp = new(big.Int).Sub(prime, bigOne)
   616  		values.Exp.Mod(priv.D, values.Exp)
   617  
   618  		values.R = new(big.Int).Set(r)
   619  		values.Coeff = new(big.Int).ModInverse(r, prime)
   620  
   621  		r.Mul(r, prime)
   622  	}
   623  }
   624  
   625  const withCheck = true
   626  const noCheck = false
   627  
   628  // decrypt performs an RSA decryption of ciphertext into out. If check is true,
   629  // m^e is calculated and compared with ciphertext, in order to defend against
   630  // errors in the CRT computation.
   631  func decrypt(priv *PrivateKey, ciphertext []byte, check bool) ([]byte, error) {
   632  	if len(priv.Primes) <= 2 {
   633  		boring.Unreachable()
   634  	}
   635  
   636  	var (
   637  		err  error
   638  		m, c *bigmod.Nat
   639  		N    *bigmod.Modulus
   640  		t0   = bigmod.NewNat()
   641  	)
   642  	if priv.Precomputed.n == nil {
   643  		N, err = bigmod.NewModulusFromBig(priv.N)
   644  		if err != nil {
   645  			return nil, ErrDecryption
   646  		}
   647  		c, err = bigmod.NewNat().SetBytes(ciphertext, N)
   648  		if err != nil {
   649  			return nil, ErrDecryption
   650  		}
   651  		m = bigmod.NewNat().Exp(c, priv.D.Bytes(), N)
   652  	} else {
   653  		N = priv.Precomputed.n
   654  		P, Q := priv.Precomputed.p, priv.Precomputed.q
   655  		Qinv, err := bigmod.NewNat().SetBytes(priv.Precomputed.Qinv.Bytes(), P)
   656  		if err != nil {
   657  			return nil, ErrDecryption
   658  		}
   659  		c, err = bigmod.NewNat().SetBytes(ciphertext, N)
   660  		if err != nil {
   661  			return nil, ErrDecryption
   662  		}
   663  
   664  		// m = c ^ Dp mod p
   665  		m = bigmod.NewNat().Exp(t0.Mod(c, P), priv.Precomputed.Dp.Bytes(), P)
   666  		// m2 = c ^ Dq mod q
   667  		m2 := bigmod.NewNat().Exp(t0.Mod(c, Q), priv.Precomputed.Dq.Bytes(), Q)
   668  		// m = m - m2 mod p
   669  		m.Sub(t0.Mod(m2, P), P)
   670  		// m = m * Qinv mod p
   671  		m.Mul(Qinv, P)
   672  		// m = m * q mod N
   673  		m.ExpandFor(N).Mul(t0.Mod(Q.Nat(), N), N)
   674  		// m = m + m2 mod N
   675  		m.Add(m2.ExpandFor(N), N)
   676  	}
   677  
   678  	if check {
   679  		c1 := bigmod.NewNat().ExpShort(m, uint(priv.E), N)
   680  		if c1.Equal(c) != 1 {
   681  			return nil, ErrDecryption
   682  		}
   683  	}
   684  
   685  	return m.Bytes(N), nil
   686  }
   687  
   688  // DecryptOAEP decrypts ciphertext using RSA-OAEP.
   689  //
   690  // OAEP is parameterised by a hash function that is used as a random oracle.
   691  // Encryption and decryption of a given message must use the same hash function
   692  // and sha256.New() is a reasonable choice.
   693  //
   694  // The random parameter is legacy and ignored, and it can be as nil.
   695  //
   696  // The label parameter must match the value given when encrypting. See
   697  // EncryptOAEP for details.
   698  func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error) {
   699  	return decryptOAEP(hash, hash, random, priv, ciphertext, label)
   700  }
   701  
   702  func decryptOAEP(hash, mgfHash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error) {
   703  	if err := checkPub(&priv.PublicKey); err != nil {
   704  		return nil, err
   705  	}
   706  	k := priv.Size()
   707  	if len(ciphertext) > k ||
   708  		k < hash.Size()*2+2 {
   709  		return nil, ErrDecryption
   710  	}
   711  
   712  	if boring.Enabled {
   713  		bkey, err := boringPrivateKey(priv)
   714  		if err != nil {
   715  			return nil, err
   716  		}
   717  		out, err := boring.DecryptRSAOAEP(hash, mgfHash, bkey, ciphertext, label)
   718  		if err != nil {
   719  			return nil, ErrDecryption
   720  		}
   721  		return out, nil
   722  	}
   723  
   724  	em, err := decrypt(priv, ciphertext, noCheck)
   725  	if err != nil {
   726  		return nil, err
   727  	}
   728  
   729  	hash.Write(label)
   730  	lHash := hash.Sum(nil)
   731  	hash.Reset()
   732  
   733  	firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
   734  
   735  	seed := em[1 : hash.Size()+1]
   736  	db := em[hash.Size()+1:]
   737  
   738  	mgf1XOR(seed, mgfHash, db)
   739  	mgf1XOR(db, mgfHash, seed)
   740  
   741  	lHash2 := db[0:hash.Size()]
   742  
   743  	// We have to validate the plaintext in constant time in order to avoid
   744  	// attacks like: J. Manger. A Chosen Ciphertext Attack on RSA Optimal
   745  	// Asymmetric Encryption Padding (OAEP) as Standardized in PKCS #1
   746  	// v2.0. In J. Kilian, editor, Advances in Cryptology.
   747  	lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2)
   748  
   749  	// The remainder of the plaintext must be zero or more 0x00, followed
   750  	// by 0x01, followed by the message.
   751  	//   lookingForIndex: 1 iff we are still looking for the 0x01
   752  	//   index: the offset of the first 0x01 byte
   753  	//   invalid: 1 iff we saw a non-zero byte before the 0x01.
   754  	var lookingForIndex, index, invalid int
   755  	lookingForIndex = 1
   756  	rest := db[hash.Size():]
   757  
   758  	for i := 0; i < len(rest); i++ {
   759  		equals0 := subtle.ConstantTimeByteEq(rest[i], 0)
   760  		equals1 := subtle.ConstantTimeByteEq(rest[i], 1)
   761  		index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index)
   762  		lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex)
   763  		invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid)
   764  	}
   765  
   766  	if firstByteIsZero&lHash2Good&^invalid&^lookingForIndex != 1 {
   767  		return nil, ErrDecryption
   768  	}
   769  
   770  	return rest[index+1:], nil
   771  }