Source file 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  // Operations involving private keys are implemented using constant-time
    23  // algorithms, except for [GenerateKey] and for some operations involving
    24  // deprecated multi-prime keys.
    25  //
    26  // # Minimum key size
    27  //
    28  // [GenerateKey] returns an error if a key of less than 1024 bits is requested,
    29  // and all Sign, Verify, Encrypt, and Decrypt methods return an error if used
    30  // with a key smaller than 1024 bits. Such keys are insecure and should not be
    31  // used.
    32  //
    33  // The rsa1024min=0 GODEBUG setting suppresses this error, but we recommend
    34  // doing so only in tests, if necessary. Tests can set this option using
    35  // [testing.T.Setenv] or by including "//go:debug rsa1024min=0" in a *_test.go
    36  // source file.
    37  //
    38  // Alternatively, see the [GenerateKey (TestKey)] example for a pregenerated
    39  // test-only 2048-bit key.
    40  //
    41  // [GenerateKey (TestKey)]: https://pkg.go.dev/crypto/rsa#example-GenerateKey-TestKey
    42  package rsa
    43  
    44  import (
    45  	"crypto"
    46  	"crypto/internal/boring"
    47  	"crypto/internal/boring/bbig"
    48  	"crypto/internal/fips140/bigmod"
    49  	"crypto/internal/fips140/rsa"
    50  	"crypto/internal/fips140only"
    51  	"crypto/internal/rand"
    52  	cryptorand "crypto/rand"
    53  	"crypto/subtle"
    54  	"errors"
    55  	"fmt"
    56  	"internal/godebug"
    57  	"io"
    58  	"math"
    59  	"math/big"
    60  )
    61  
    62  var bigOne = big.NewInt(1)
    63  
    64  // A PublicKey represents the public part of an RSA key.
    65  //
    66  // The values of N and E are not considered confidential, and may leak through
    67  // side channels, or could be mathematically derived from other public values.
    68  type PublicKey struct {
    69  	N *big.Int // modulus
    70  	E int      // public exponent
    71  }
    72  
    73  // Any methods implemented on PublicKey might need to also be implemented on
    74  // PrivateKey, as the latter embeds the former and will expose its methods.
    75  
    76  // Size returns the modulus size in bytes. Raw signatures and ciphertexts
    77  // for or by this public key will have the same size.
    78  func (pub *PublicKey) Size() int {
    79  	return (pub.N.BitLen() + 7) / 8
    80  }
    81  
    82  // Equal reports whether pub and x have the same value.
    83  func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
    84  	xx, ok := x.(*PublicKey)
    85  	if !ok {
    86  		return false
    87  	}
    88  	return bigIntEqual(pub.N, xx.N) && pub.E == xx.E
    89  }
    90  
    91  // OAEPOptions allows passing options to OAEP encryption and decryption
    92  // through the [PrivateKey.Decrypt] and [EncryptOAEPWithOptions] functions.
    93  type OAEPOptions struct {
    94  	// Hash is the hash function that will be used when generating the mask.
    95  	Hash crypto.Hash
    96  
    97  	// MGFHash is the hash function used for MGF1.
    98  	// If zero, Hash is used instead.
    99  	MGFHash crypto.Hash
   100  
   101  	// Label is an arbitrary byte string that must be equal to the value
   102  	// used when encrypting.
   103  	Label []byte
   104  }
   105  
   106  // A PrivateKey represents an RSA key.
   107  //
   108  // Its fields must not be modified after calling [PrivateKey.Precompute], and
   109  // should not be used directly as big.Int values for cryptographic purposes.
   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 afterwards.
   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.Hash.Available() {
   180  			return nil, errors.New("rsa: requested hash function unavailable: " + opts.Hash.String())
   181  		}
   182  		if opts.MGFHash != 0 && !opts.MGFHash.Available() {
   183  			return nil, errors.New("rsa: requested hash function unavailable: " + opts.MGFHash.String())
   184  		}
   185  		if opts.MGFHash == 0 {
   186  			return decryptOAEP(opts.Hash.New(), opts.Hash.New(), priv, ciphertext, opts.Label)
   187  		} else {
   188  			return decryptOAEP(opts.Hash.New(), opts.MGFHash.New(), priv, ciphertext, opts.Label)
   189  		}
   190  
   191  	case *PKCS1v15DecryptOptions:
   192  		if l := opts.SessionKeyLen; l > 0 {
   193  			plaintext = make([]byte, l)
   194  			if _, err := io.ReadFull(rand, plaintext); err != nil {
   195  				return nil, err
   196  			}
   197  			if err := DecryptPKCS1v15SessionKey(rand, priv, ciphertext, plaintext); err != nil {
   198  				return nil, err
   199  			}
   200  			return plaintext, nil
   201  		} else {
   202  			return DecryptPKCS1v15(rand, priv, ciphertext)
   203  		}
   204  
   205  	default:
   206  		return nil, errors.New("crypto/rsa: invalid options for Decrypt")
   207  	}
   208  }
   209  
   210  type PrecomputedValues struct {
   211  	Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
   212  	Qinv   *big.Int // Q^-1 mod P
   213  
   214  	// CRTValues is used for the 3rd and subsequent primes. Due to a
   215  	// historical accident, the CRT for the first two primes is handled
   216  	// differently in PKCS #1 and interoperability is sufficiently
   217  	// important that we mirror this.
   218  	//
   219  	// Deprecated: These values are still filled in by Precompute for
   220  	// backwards compatibility but are not used. Multi-prime RSA is very rare,
   221  	// and is implemented by this package without CRT optimizations to limit
   222  	// complexity.
   223  	CRTValues []CRTValue
   224  
   225  	fips *rsa.PrivateKey
   226  }
   227  
   228  // CRTValue contains the precomputed Chinese remainder theorem values.
   229  type CRTValue struct {
   230  	Exp   *big.Int // D mod (prime-1).
   231  	Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
   232  	R     *big.Int // product of primes prior to this (inc p and q).
   233  }
   234  
   235  // Validate performs basic sanity checks on the key.
   236  // It returns nil if the key is valid, or else an error describing a problem.
   237  //
   238  // It runs faster on valid keys if run after [PrivateKey.Precompute].
   239  func (priv *PrivateKey) Validate() error {
   240  	// We can operate on keys based on d alone, but they can't be encoded with
   241  	// [crypto/x509.MarshalPKCS1PrivateKey], which unfortunately doesn't return
   242  	// an error, so we need to reject them here.
   243  	if len(priv.Primes) < 2 {
   244  		return errors.New("crypto/rsa: missing primes")
   245  	}
   246  	// If Precomputed.fips is set and consistent, then the key has been
   247  	// validated by [rsa.NewPrivateKey] or [rsa.NewPrivateKeyWithoutCRT].
   248  	if priv.precomputedIsConsistent() {
   249  		return nil
   250  	}
   251  	if priv.Precomputed.fips != nil {
   252  		return errors.New("crypto/rsa: precomputed values are inconsistent with the key")
   253  	}
   254  	_, err := priv.precompute()
   255  	return err
   256  }
   257  
   258  func (priv *PrivateKey) precomputedIsConsistent() bool {
   259  	if priv.Precomputed.fips == nil {
   260  		return false
   261  	}
   262  	N, e, d, P, Q, dP, dQ, qInv := priv.Precomputed.fips.Export()
   263  	if !bigIntEqualToBytes(priv.N, N) || priv.E != e || !bigIntEqualToBytes(priv.D, d) {
   264  		return false
   265  	}
   266  	if len(priv.Primes) != 2 {
   267  		return P == nil && Q == nil && dP == nil && dQ == nil && qInv == nil
   268  	}
   269  	return bigIntEqualToBytes(priv.Primes[0], P) &&
   270  		bigIntEqualToBytes(priv.Primes[1], Q) &&
   271  		bigIntEqualToBytes(priv.Precomputed.Dp, dP) &&
   272  		bigIntEqualToBytes(priv.Precomputed.Dq, dQ) &&
   273  		bigIntEqualToBytes(priv.Precomputed.Qinv, qInv)
   274  }
   275  
   276  // bigIntEqual reports whether a and b are equal, ignoring leading zero bytes in
   277  // b, and leaking only their bit length through timing side-channels.
   278  func bigIntEqualToBytes(a *big.Int, b []byte) bool {
   279  	if a == nil || a.BitLen() > len(b)*8 {
   280  		return false
   281  	}
   282  	buf := a.FillBytes(make([]byte, len(b)))
   283  	return subtle.ConstantTimeCompare(buf, b) == 1
   284  }
   285  
   286  // rsa1024min is a GODEBUG that re-enables weak RSA keys if set to "0".
   287  // See https://go.dev/issue/68762.
   288  var rsa1024min = godebug.New("rsa1024min")
   289  
   290  func checkKeySize(size int) error {
   291  	if size >= 1024 {
   292  		return nil
   293  	}
   294  	if rsa1024min.Value() == "0" {
   295  		rsa1024min.IncNonDefault()
   296  		return nil
   297  	}
   298  	return fmt.Errorf("crypto/rsa: %d-bit keys are insecure (see https://go.dev/pkg/crypto/rsa#hdr-Minimum_key_size)", size)
   299  }
   300  
   301  func checkPublicKeySize(k *PublicKey) error {
   302  	if k.N == nil {
   303  		return errors.New("crypto/rsa: missing public modulus")
   304  	}
   305  	return checkKeySize(k.N.BitLen())
   306  }
   307  
   308  // GenerateKey generates a random RSA private key of the given bit size.
   309  //
   310  // If bits is less than 1024, [GenerateKey] returns an error. See the "[Minimum
   311  // key size]" section for further details.
   312  //
   313  // Since Go 1.26, a secure source of random bytes is always used, and the Reader is
   314  // ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be removed
   315  // in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom].
   316  //
   317  // [Minimum key size]: https://pkg.go.dev/crypto/rsa#hdr-Minimum_key_size
   318  func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) {
   319  	if err := checkKeySize(bits); err != nil {
   320  		return nil, err
   321  	}
   322  
   323  	if boring.Enabled && rand.IsDefaultReader(random) &&
   324  		(bits == 2048 || bits == 3072 || bits == 4096) {
   325  		bN, bE, bD, bP, bQ, bDp, bDq, bQinv, err := boring.GenerateKeyRSA(bits)
   326  		if err != nil {
   327  			return nil, err
   328  		}
   329  		N := bbig.Dec(bN)
   330  		E := bbig.Dec(bE)
   331  		D := bbig.Dec(bD)
   332  		P := bbig.Dec(bP)
   333  		Q := bbig.Dec(bQ)
   334  		Dp := bbig.Dec(bDp)
   335  		Dq := bbig.Dec(bDq)
   336  		Qinv := bbig.Dec(bQinv)
   337  		e64 := E.Int64()
   338  		if !E.IsInt64() || int64(int(e64)) != e64 {
   339  			return nil, errors.New("crypto/rsa: generated key exponent too large")
   340  		}
   341  
   342  		key := &PrivateKey{
   343  			PublicKey: PublicKey{
   344  				N: N,
   345  				E: int(e64),
   346  			},
   347  			D:      D,
   348  			Primes: []*big.Int{P, Q},
   349  			Precomputed: PrecomputedValues{
   350  				Dp:        Dp,
   351  				Dq:        Dq,
   352  				Qinv:      Qinv,
   353  				CRTValues: make([]CRTValue, 0), // non-nil, to match Precompute
   354  			},
   355  		}
   356  		return key, nil
   357  	}
   358  
   359  	random = rand.CustomReader(random)
   360  
   361  	if fips140only.Enforced() && bits < 2048 {
   362  		return nil, errors.New("crypto/rsa: use of keys smaller than 2048 bits is not allowed in FIPS 140-only mode")
   363  	}
   364  	if fips140only.Enforced() && bits%2 == 1 {
   365  		return nil, errors.New("crypto/rsa: use of keys with odd size is not allowed in FIPS 140-only mode")
   366  	}
   367  	if fips140only.Enforced() && !fips140only.ApprovedRandomReader(random) {
   368  		return nil, errors.New("crypto/rsa: only crypto/rand.Reader is allowed in FIPS 140-only mode")
   369  	}
   370  
   371  	k, err := rsa.GenerateKey(random, bits)
   372  	if bits < 256 && err != nil {
   373  		// Toy-sized keys have a non-negligible chance of hitting two hard
   374  		// failure cases: p == q and d <= 2^(nlen / 2).
   375  		//
   376  		// Since these are impossible to hit for real keys, we don't want to
   377  		// make the production code path more complex and harder to think about
   378  		// to handle them.
   379  		//
   380  		// Instead, just rerun the whole process a total of 8 times, which
   381  		// brings the chance of failure for 32-bit keys down to the same as for
   382  		// 256-bit keys.
   383  		for i := 1; i < 8 && err != nil; i++ {
   384  			k, err = rsa.GenerateKey(random, bits)
   385  		}
   386  	}
   387  	if err != nil {
   388  		return nil, err
   389  	}
   390  	N, e, d, p, q, dP, dQ, qInv := k.Export()
   391  	key := &PrivateKey{
   392  		PublicKey: PublicKey{
   393  			N: new(big.Int).SetBytes(N),
   394  			E: e,
   395  		},
   396  		D: new(big.Int).SetBytes(d),
   397  		Primes: []*big.Int{
   398  			new(big.Int).SetBytes(p),
   399  			new(big.Int).SetBytes(q),
   400  		},
   401  		Precomputed: PrecomputedValues{
   402  			fips:      k,
   403  			Dp:        new(big.Int).SetBytes(dP),
   404  			Dq:        new(big.Int).SetBytes(dQ),
   405  			Qinv:      new(big.Int).SetBytes(qInv),
   406  			CRTValues: make([]CRTValue, 0), // non-nil, to match Precompute
   407  		},
   408  	}
   409  	return key, nil
   410  }
   411  
   412  // GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit
   413  // size and the given random source.
   414  //
   415  // Table 1 in "[On the Security of Multi-prime RSA]" suggests maximum numbers of
   416  // primes for a given bit size.
   417  //
   418  // Although the public keys are compatible (actually, indistinguishable) from
   419  // the 2-prime case, the private keys are not. Thus it may not be possible to
   420  // export multi-prime private keys in certain formats or to subsequently import
   421  // them into other code.
   422  //
   423  // This package does not implement CRT optimizations for multi-prime RSA, so the
   424  // keys with more than two primes will have worse performance.
   425  //
   426  // Since Go 1.26, a secure source of random bytes is always used, and the Reader is
   427  // ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be removed
   428  // in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom].
   429  //
   430  // Deprecated: The use of this function with a number of primes different from
   431  // two is not recommended for the above security, compatibility, and performance
   432  // reasons. Use [GenerateKey] instead.
   433  //
   434  // [On the Security of Multi-prime RSA]: http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
   435  func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error) {
   436  	if nprimes == 2 {
   437  		return GenerateKey(random, bits)
   438  	}
   439  	if fips140only.Enforced() {
   440  		return nil, errors.New("crypto/rsa: multi-prime RSA is not allowed in FIPS 140-only mode")
   441  	}
   442  
   443  	random = rand.CustomReader(random)
   444  
   445  	priv := new(PrivateKey)
   446  	priv.E = 65537
   447  
   448  	if nprimes < 2 {
   449  		return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
   450  	}
   451  
   452  	if bits < 64 {
   453  		primeLimit := float64(uint64(1) << uint(bits/nprimes))
   454  		// pi approximates the number of primes less than primeLimit
   455  		pi := primeLimit / (math.Log(primeLimit) - 1)
   456  		// Generated primes start with 11 (in binary) so we can only
   457  		// use a quarter of them.
   458  		pi /= 4
   459  		// Use a factor of two to ensure that key generation terminates
   460  		// in a reasonable amount of time.
   461  		pi /= 2
   462  		if pi <= float64(nprimes) {
   463  			return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key")
   464  		}
   465  	}
   466  
   467  	primes := make([]*big.Int, nprimes)
   468  
   469  NextSetOfPrimes:
   470  	for {
   471  		todo := bits
   472  		// crypto/rand should set the top two bits in each prime.
   473  		// Thus each prime has the form
   474  		//   p_i = 2^bitlen(p_i) × 0.11... (in base 2).
   475  		// And the product is:
   476  		//   P = 2^todo × α
   477  		// where α is the product of nprimes numbers of the form 0.11...
   478  		//
   479  		// If α < 1/2 (which can happen for nprimes > 2), we need to
   480  		// shift todo to compensate for lost bits: the mean value of 0.11...
   481  		// is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2
   482  		// will give good results.
   483  		if nprimes >= 7 {
   484  			todo += (nprimes - 2) / 5
   485  		}
   486  		for i := 0; i < nprimes; i++ {
   487  			var err error
   488  			primes[i], err = cryptorand.Prime(random, todo/(nprimes-i))
   489  			if err != nil {
   490  				return nil, err
   491  			}
   492  			todo -= primes[i].BitLen()
   493  		}
   494  
   495  		// Make sure that primes is pairwise unequal.
   496  		for i, prime := range primes {
   497  			for j := 0; j < i; j++ {
   498  				if prime.Cmp(primes[j]) == 0 {
   499  					continue NextSetOfPrimes
   500  				}
   501  			}
   502  		}
   503  
   504  		n := new(big.Int).Set(bigOne)
   505  		totient := new(big.Int).Set(bigOne)
   506  		pminus1 := new(big.Int)
   507  		for _, prime := range primes {
   508  			n.Mul(n, prime)
   509  			pminus1.Sub(prime, bigOne)
   510  			totient.Mul(totient, pminus1)
   511  		}
   512  		if n.BitLen() != bits {
   513  			// This should never happen for nprimes == 2 because
   514  			// crypto/rand should set the top two bits in each prime.
   515  			// For nprimes > 2 we hope it does not happen often.
   516  			continue NextSetOfPrimes
   517  		}
   518  
   519  		priv.D = new(big.Int)
   520  		e := big.NewInt(int64(priv.E))
   521  		ok := priv.D.ModInverse(e, totient)
   522  
   523  		if ok != nil {
   524  			priv.Primes = primes
   525  			priv.N = n
   526  			break
   527  		}
   528  	}
   529  
   530  	priv.Precompute()
   531  	if err := priv.Validate(); err != nil {
   532  		return nil, err
   533  	}
   534  
   535  	return priv, nil
   536  }
   537  
   538  // ErrMessageTooLong is returned when attempting to encrypt or sign a message
   539  // which is too large for the size of the key. When using [SignPSS], this can also
   540  // be returned if the size of the salt is too large.
   541  var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")
   542  
   543  // ErrDecryption represents a failure to decrypt a message.
   544  // It is deliberately vague to avoid adaptive attacks.
   545  var ErrDecryption = errors.New("crypto/rsa: decryption error")
   546  
   547  // ErrVerification represents a failure to verify a signature.
   548  // It is deliberately vague to avoid adaptive attacks.
   549  var ErrVerification = errors.New("crypto/rsa: verification error")
   550  
   551  // Precompute performs some calculations that speed up private key operations in
   552  // the future. It is safe to run on non-validated private keys, and it can speed
   553  // up future calls to [PrivateKey.Validate] for valid keys.
   554  //
   555  // Precompute writes to the Precomputed field, so it must not be called
   556  // concurrently with any other method.
   557  //
   558  // Precompute does not return an error. Applications should call
   559  // [PrivateKey.Validate] after Precompute to check for any problems with the
   560  // key, including any that would cause Precompute to fail.
   561  //
   562  // Calling Precompute on a key that has already been precomputed is a no-op.
   563  func (priv *PrivateKey) Precompute() {
   564  	if priv.precomputedIsConsistent() {
   565  		return
   566  	}
   567  
   568  	precomputed, err := priv.precompute()
   569  	if err != nil {
   570  		// We don't have a way to report errors, so just leave Precomputed.fips
   571  		// nil. Validate will re-run precompute and report its error.
   572  		priv.Precomputed.fips = nil
   573  		return
   574  	}
   575  	priv.Precomputed = precomputed
   576  }
   577  
   578  // precompute calculates the PrecomputedValues for priv and returns them.
   579  //
   580  // It does NOT modify priv and is safe for concurrent use.
   581  func (priv *PrivateKey) precompute() (PrecomputedValues, error) {
   582  	var precomputed PrecomputedValues
   583  
   584  	if priv.N == nil {
   585  		return precomputed, errors.New("crypto/rsa: missing public modulus")
   586  	}
   587  	if priv.D == nil {
   588  		return precomputed, errors.New("crypto/rsa: missing private exponent")
   589  	}
   590  	if len(priv.Primes) != 2 {
   591  		return priv.precomputeLegacy()
   592  	}
   593  	if priv.Primes[0] == nil {
   594  		return precomputed, errors.New("crypto/rsa: prime P is nil")
   595  	}
   596  	if priv.Primes[1] == nil {
   597  		return precomputed, errors.New("crypto/rsa: prime Q is nil")
   598  	}
   599  
   600  	// If the CRT values are already set, use them.
   601  	if priv.Precomputed.Dp != nil && priv.Precomputed.Dq != nil && priv.Precomputed.Qinv != nil {
   602  		k, err := rsa.NewPrivateKeyWithPrecomputation(priv.N.Bytes(), priv.E, priv.D.Bytes(),
   603  			priv.Primes[0].Bytes(), priv.Primes[1].Bytes(),
   604  			priv.Precomputed.Dp.Bytes(), priv.Precomputed.Dq.Bytes(), priv.Precomputed.Qinv.Bytes())
   605  		if err != nil {
   606  			return precomputed, err
   607  		}
   608  		precomputed = priv.Precomputed
   609  		precomputed.fips = k
   610  		precomputed.CRTValues = make([]CRTValue, 0)
   611  		return precomputed, nil
   612  	}
   613  
   614  	k, err := rsa.NewPrivateKey(priv.N.Bytes(), priv.E, priv.D.Bytes(),
   615  		priv.Primes[0].Bytes(), priv.Primes[1].Bytes())
   616  	if err != nil {
   617  		return precomputed, err
   618  	}
   619  
   620  	precomputed.fips = k
   621  	_, _, _, _, _, dP, dQ, qInv := k.Export()
   622  	precomputed.Dp = new(big.Int).SetBytes(dP)
   623  	precomputed.Dq = new(big.Int).SetBytes(dQ)
   624  	precomputed.Qinv = new(big.Int).SetBytes(qInv)
   625  	precomputed.CRTValues = make([]CRTValue, 0)
   626  	return precomputed, nil
   627  }
   628  
   629  func (priv *PrivateKey) precomputeLegacy() (PrecomputedValues, error) {
   630  	var precomputed PrecomputedValues
   631  
   632  	k, err := rsa.NewPrivateKeyWithoutCRT(priv.N.Bytes(), priv.E, priv.D.Bytes())
   633  	if err != nil {
   634  		return precomputed, err
   635  	}
   636  	precomputed.fips = k
   637  
   638  	if len(priv.Primes) < 2 {
   639  		return precomputed, nil
   640  	}
   641  
   642  	// Ensure the Mod and ModInverse calls below don't panic.
   643  	for _, prime := range priv.Primes {
   644  		if prime == nil {
   645  			return precomputed, errors.New("crypto/rsa: prime factor is nil")
   646  		}
   647  		if prime.Cmp(bigOne) <= 0 {
   648  			return precomputed, errors.New("crypto/rsa: prime factor is <= 1")
   649  		}
   650  	}
   651  
   652  	precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
   653  	precomputed.Dp.Mod(priv.D, precomputed.Dp)
   654  
   655  	precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
   656  	precomputed.Dq.Mod(priv.D, precomputed.Dq)
   657  
   658  	precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])
   659  	if precomputed.Qinv == nil {
   660  		return precomputed, errors.New("crypto/rsa: prime factors are not relatively prime")
   661  	}
   662  
   663  	r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])
   664  	precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2)
   665  	for i := 2; i < len(priv.Primes); i++ {
   666  		prime := priv.Primes[i]
   667  		values := &precomputed.CRTValues[i-2]
   668  
   669  		values.Exp = new(big.Int).Sub(prime, bigOne)
   670  		values.Exp.Mod(priv.D, values.Exp)
   671  
   672  		values.R = new(big.Int).Set(r)
   673  		values.Coeff = new(big.Int).ModInverse(r, prime)
   674  		if values.Coeff == nil {
   675  			return precomputed, errors.New("crypto/rsa: prime factors are not relatively prime")
   676  		}
   677  
   678  		r.Mul(r, prime)
   679  	}
   680  
   681  	return precomputed, nil
   682  }
   683  
   684  func fipsPublicKey(pub *PublicKey) (*rsa.PublicKey, error) {
   685  	N, err := bigmod.NewModulus(pub.N.Bytes())
   686  	if err != nil {
   687  		return nil, err
   688  	}
   689  	return &rsa.PublicKey{N: N, E: pub.E}, nil
   690  }
   691  
   692  // fipsPrivateKey returns the *rsa.PrivateKey corresponding to priv, using the
   693  // precomputed values if available, and calculating them if not.
   694  //
   695  // It does NOT modify priv and is safe for concurrent use.
   696  func fipsPrivateKey(priv *PrivateKey) (*rsa.PrivateKey, error) {
   697  	if priv.Precomputed.fips != nil {
   698  		return priv.Precomputed.fips, nil
   699  	}
   700  	precomputed, err := priv.precompute()
   701  	if err != nil {
   702  		return nil, err
   703  	}
   704  	return precomputed.fips, nil
   705  }
   706  

View as plain text