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