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