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