| 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.MGFHash == 0 { |
| 180 |
return decryptOAEP(opts.Hash.New(), opts.Hash.New(), priv, ciphertext, opts.Label) |
| 181 |
} else { |
| 182 |
return decryptOAEP(opts.Hash.New(), opts.MGFHash.New(), 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 |
fips *rsa.PrivateKey |
| 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 |
// |
| 232 |
// It runs faster on valid keys if run after [PrivateKey.Precompute]. |
| 233 |
func (priv *PrivateKey) Validate() error { |
| 234 |
// We can operate on keys based on d alone, but they can't be encoded with |
| 235 |
// [crypto/x509.MarshalPKCS1PrivateKey], which unfortunately doesn't return |
| 236 |
// an error, so we need to reject them here. |
| 237 |
if len(priv.Primes) < 2 { |
| 238 |
return errors.New("crypto/rsa: missing primes") |
| 239 |
} |
| 240 |
// If Precomputed.fips is set and consistent, then the key has been |
| 241 |
// validated by [rsa.NewPrivateKey] or [rsa.NewPrivateKeyWithoutCRT]. |
| 242 |
if priv.precomputedIsConsistent() { |
| 243 |
return nil |
| 244 |
} |
| 245 |
if priv.Precomputed.fips != nil { |
| 246 |
return errors.New("crypto/rsa: precomputed values are inconsistent with the key") |
| 247 |
} |
| 248 |
_, err := priv.precompute() |
| 249 |
return err |
| 250 |
} |
| 251 |
|
| 252 |
func (priv *PrivateKey) precomputedIsConsistent() bool { |
| 253 |
if priv.Precomputed.fips == nil { |
| 254 |
return false |
| 255 |
} |
| 256 |
N, e, d, P, Q, dP, dQ, qInv := priv.Precomputed.fips.Export() |
| 257 |
if !bigIntEqualToBytes(priv.N, N) || priv.E != e || !bigIntEqualToBytes(priv.D, d) { |
| 258 |
return false |
| 259 |
} |
| 260 |
if len(priv.Primes) != 2 { |
| 261 |
return P == nil && Q == nil && dP == nil && dQ == nil && qInv == nil |
| 262 |
} |
| 263 |
return bigIntEqualToBytes(priv.Primes[0], P) && |
| 264 |
bigIntEqualToBytes(priv.Primes[1], Q) && |
| 265 |
bigIntEqualToBytes(priv.Precomputed.Dp, dP) && |
| 266 |
bigIntEqualToBytes(priv.Precomputed.Dq, dQ) && |
| 267 |
bigIntEqualToBytes(priv.Precomputed.Qinv, qInv) |
| 268 |
} |
| 269 |
|
| 270 |
// bigIntEqual reports whether a and b are equal, ignoring leading zero bytes in |
| 271 |
// b, and leaking only their bit length through timing side-channels. |
| 272 |
func bigIntEqualToBytes(a *big.Int, b []byte) bool { |
| 273 |
if a == nil || a.BitLen() > len(b)*8 { |
| 274 |
return false |
| 275 |
} |
| 276 |
buf := a.FillBytes(make([]byte, len(b))) |
| 277 |
return subtle.ConstantTimeCompare(buf, b) == 1 |
| 278 |
} |
| 279 |
|
| 280 |
// rsa1024min is a GODEBUG that re-enables weak RSA keys if set to "0". |
| 281 |
// See https://go.dev/issue/68762. |
| 282 |
var rsa1024min = godebug.New("rsa1024min") |
| 283 |
|
| 284 |
func checkKeySize(size int) error { |
| 285 |
if size >= 1024 { |
| 286 |
return nil |
| 287 |
} |
| 288 |
if rsa1024min.Value() == "0" { |
| 289 |
rsa1024min.IncNonDefault() |
| 290 |
return nil |
| 291 |
} |
| 292 |
return fmt.Errorf("crypto/rsa: %d-bit keys are insecure (see https://go.dev/pkg/crypto/rsa#hdr-Minimum_key_size)", size) |
| 293 |
} |
| 294 |
|
| 295 |
func checkPublicKeySize(k *PublicKey) error { |
| 296 |
if k.N == nil { |
| 297 |
return errors.New("crypto/rsa: missing public modulus") |
| 298 |
} |
| 299 |
return checkKeySize(k.N.BitLen()) |
| 300 |
} |
| 301 |
|
| 302 |
// GenerateKey generates a random RSA private key of the given bit size. |
| 303 |
// |
| 304 |
// If bits is less than 1024, [GenerateKey] returns an error. See the "[Minimum |
| 305 |
// key size]" section for further details. |
| 306 |
// |
| 307 |
// Since Go 1.26, a secure source of random bytes is always used, and the Reader is |
| 308 |
// ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be removed |
| 309 |
// in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom]. |
| 310 |
// |
| 311 |
// [Minimum key size]: https://pkg.go.dev/crypto/rsa#hdr-Minimum_key_size |
| 312 |
func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) { |
| 313 |
if err := checkKeySize(bits); err != nil { |
| 314 |
return nil, err |
| 315 |
} |
| 316 |
|
| 317 |
if boring.Enabled && rand.IsDefaultReader(random) && |
| 318 |
(bits == 2048 || bits == 3072 || bits == 4096) { |
| 319 |
bN, bE, bD, bP, bQ, bDp, bDq, bQinv, err := boring.GenerateKeyRSA(bits) |
| 320 |
if err != nil { |
| 321 |
return nil, err |
| 322 |
} |
| 323 |
N := bbig.Dec(bN) |
| 324 |
E := bbig.Dec(bE) |
| 325 |
D := bbig.Dec(bD) |
| 326 |
P := bbig.Dec(bP) |
| 327 |
Q := bbig.Dec(bQ) |
| 328 |
Dp := bbig.Dec(bDp) |
| 329 |
Dq := bbig.Dec(bDq) |
| 330 |
Qinv := bbig.Dec(bQinv) |
| 331 |
e64 := E.Int64() |
| 332 |
if !E.IsInt64() || int64(int(e64)) != e64 { |
| 333 |
return nil, errors.New("crypto/rsa: generated key exponent too large") |
| 334 |
} |
| 335 |
|
| 336 |
key := &PrivateKey{ |
| 337 |
PublicKey: PublicKey{ |
| 338 |
N: N, |
| 339 |
E: int(e64), |
| 340 |
}, |
| 341 |
D: D, |
| 342 |
Primes: []*big.Int{P, Q}, |
| 343 |
Precomputed: PrecomputedValues{ |
| 344 |
Dp: Dp, |
| 345 |
Dq: Dq, |
| 346 |
Qinv: Qinv, |
| 347 |
CRTValues: make([]CRTValue, 0), // non-nil, to match Precompute |
| 348 |
}, |
| 349 |
} |
| 350 |
return key, nil |
| 351 |
} |
| 352 |
|
| 353 |
random = rand.CustomReader(random) |
| 354 |
|
| 355 |
if fips140only.Enforced() && bits < 2048 { |
| 356 |
return nil, errors.New("crypto/rsa: use of keys smaller than 2048 bits is not allowed in FIPS 140-only mode") |
| 357 |
} |
| 358 |
if fips140only.Enforced() && bits%2 == 1 { |
| 359 |
return nil, errors.New("crypto/rsa: use of keys with odd size is not allowed in FIPS 140-only mode") |
| 360 |
} |
| 361 |
if fips140only.Enforced() && !fips140only.ApprovedRandomReader(random) { |
| 362 |
return nil, errors.New("crypto/rsa: only crypto/rand.Reader is allowed in FIPS 140-only mode") |
| 363 |
} |
| 364 |
|
| 365 |
k, err := rsa.GenerateKey(random, bits) |
| 366 |
if bits < 256 && err != nil { |
| 367 |
// Toy-sized keys have a non-negligible chance of hitting two hard |
| 368 |
// failure cases: p == q and d <= 2^(nlen / 2). |
| 369 |
// |
| 370 |
// Since these are impossible to hit for real keys, we don't want to |
| 371 |
// make the production code path more complex and harder to think about |
| 372 |
// to handle them. |
| 373 |
// |
| 374 |
// Instead, just rerun the whole process a total of 8 times, which |
| 375 |
// brings the chance of failure for 32-bit keys down to the same as for |
| 376 |
// 256-bit keys. |
| 377 |
for i := 1; i < 8 && err != nil; i++ { |
| 378 |
k, err = rsa.GenerateKey(random, bits) |
| 379 |
} |
| 380 |
} |
| 381 |
if err != nil { |
| 382 |
return nil, err |
| 383 |
} |
| 384 |
N, e, d, p, q, dP, dQ, qInv := k.Export() |
| 385 |
key := &PrivateKey{ |
| 386 |
PublicKey: PublicKey{ |
| 387 |
N: new(big.Int).SetBytes(N), |
| 388 |
E: e, |
| 389 |
}, |
| 390 |
D: new(big.Int).SetBytes(d), |
| 391 |
Primes: []*big.Int{ |
| 392 |
new(big.Int).SetBytes(p), |
| 393 |
new(big.Int).SetBytes(q), |
| 394 |
}, |
| 395 |
Precomputed: PrecomputedValues{ |
| 396 |
fips: k, |
| 397 |
Dp: new(big.Int).SetBytes(dP), |
| 398 |
Dq: new(big.Int).SetBytes(dQ), |
| 399 |
Qinv: new(big.Int).SetBytes(qInv), |
| 400 |
CRTValues: make([]CRTValue, 0), // non-nil, to match Precompute |
| 401 |
}, |
| 402 |
} |
| 403 |
return key, nil |
| 404 |
} |
| 405 |
|
| 406 |
// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit |
| 407 |
// size and the given random source. |
| 408 |
// |
| 409 |
// Table 1 in "[On the Security of Multi-prime RSA]" suggests maximum numbers of |
| 410 |
// primes for a given bit size. |
| 411 |
// |
| 412 |
// Although the public keys are compatible (actually, indistinguishable) from |
| 413 |
// the 2-prime case, the private keys are not. Thus it may not be possible to |
| 414 |
// export multi-prime private keys in certain formats or to subsequently import |
| 415 |
// them into other code. |
| 416 |
// |
| 417 |
// This package does not implement CRT optimizations for multi-prime RSA, so the |
| 418 |
// keys with more than two primes will have worse performance. |
| 419 |
// |
| 420 |
// Since Go 1.26, a secure source of random bytes is always used, and the Reader is |
| 421 |
// ignored unless GODEBUG=cryptocustomrand=1 is set. This setting will be removed |
| 422 |
// in a future Go release. Instead, use [testing/cryptotest.SetGlobalRandom]. |
| 423 |
// |
| 424 |
// Deprecated: The use of this function with a number of primes different from |
| 425 |
// two is not recommended for the above security, compatibility, and performance |
| 426 |
// reasons. Use [GenerateKey] instead. |
| 427 |
// |
| 428 |
// [On the Security of Multi-prime RSA]: http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf |
| 429 |
func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error) { |
| 430 |
if nprimes == 2 { |
| 431 |
return GenerateKey(random, bits) |
| 432 |
} |
| 433 |
if fips140only.Enforced() { |
| 434 |
return nil, errors.New("crypto/rsa: multi-prime RSA is not allowed in FIPS 140-only mode") |
| 435 |
} |
| 436 |
|
| 437 |
random = rand.CustomReader(random) |
| 438 |
|
| 439 |
priv := new(PrivateKey) |
| 440 |
priv.E = 65537 |
| 441 |
|
| 442 |
if nprimes < 2 { |
| 443 |
return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2") |
| 444 |
} |
| 445 |
|
| 446 |
if bits < 64 { |
| 447 |
primeLimit := float64(uint64(1) << uint(bits/nprimes)) |
| 448 |
// pi approximates the number of primes less than primeLimit |
| 449 |
pi := primeLimit / (math.Log(primeLimit) - 1) |
| 450 |
// Generated primes start with 11 (in binary) so we can only |
| 451 |
// use a quarter of them. |
| 452 |
pi /= 4 |
| 453 |
// Use a factor of two to ensure that key generation terminates |
| 454 |
// in a reasonable amount of time. |
| 455 |
pi /= 2 |
| 456 |
if pi <= float64(nprimes) { |
| 457 |
return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key") |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
primes := make([]*big.Int, nprimes) |
| 462 |
|
| 463 |
NextSetOfPrimes: |
| 464 |
for { |
| 465 |
todo := bits |
| 466 |
// crypto/rand should set the top two bits in each prime. |
| 467 |
// Thus each prime has the form |
| 468 |
// p_i = 2^bitlen(p_i) × 0.11... (in base 2). |
| 469 |
// And the product is: |
| 470 |
// P = 2^todo × α |
| 471 |
// where α is the product of nprimes numbers of the form 0.11... |
| 472 |
// |
| 473 |
// If α < 1/2 (which can happen for nprimes > 2), we need to |
| 474 |
// shift todo to compensate for lost bits: the mean value of 0.11... |
| 475 |
// is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 |
| 476 |
// will give good results. |
| 477 |
if nprimes >= 7 { |
| 478 |
todo += (nprimes - 2) / 5 |
| 479 |
} |
| 480 |
for i := 0; i < nprimes; i++ { |
| 481 |
var err error |
| 482 |
primes[i], err = cryptorand.Prime(random, todo/(nprimes-i)) |
| 483 |
if err != nil { |
| 484 |
return nil, err |
| 485 |
} |
| 486 |
todo -= primes[i].BitLen() |
| 487 |
} |
| 488 |
|
| 489 |
// Make sure that primes is pairwise unequal. |
| 490 |
for i, prime := range primes { |
| 491 |
for j := 0; j < i; j++ { |
| 492 |
if prime.Cmp(primes[j]) == 0 { |
| 493 |
continue NextSetOfPrimes |
| 494 |
} |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
n := new(big.Int).Set(bigOne) |
| 499 |
totient := new(big.Int).Set(bigOne) |
| 500 |
pminus1 := new(big.Int) |
| 501 |
for _, prime := range primes { |
| 502 |
n.Mul(n, prime) |
| 503 |
pminus1.Sub(prime, bigOne) |
| 504 |
totient.Mul(totient, pminus1) |
| 505 |
} |
| 506 |
if n.BitLen() != bits { |
| 507 |
// This should never happen for nprimes == 2 because |
| 508 |
// crypto/rand should set the top two bits in each prime. |
| 509 |
// For nprimes > 2 we hope it does not happen often. |
| 510 |
continue NextSetOfPrimes |
| 511 |
} |
| 512 |
|
| 513 |
priv.D = new(big.Int) |
| 514 |
e := big.NewInt(int64(priv.E)) |
| 515 |
ok := priv.D.ModInverse(e, totient) |
| 516 |
|
| 517 |
if ok != nil { |
| 518 |
priv.Primes = primes |
| 519 |
priv.N = n |
| 520 |
break |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
priv.Precompute() |
| 525 |
if err := priv.Validate(); err != nil { |
| 526 |
return nil, err |
| 527 |
} |
| 528 |
|
| 529 |
return priv, nil |
| 530 |
} |
| 531 |
|
| 532 |
// ErrMessageTooLong is returned when attempting to encrypt or sign a message |
| 533 |
// which is too large for the size of the key. When using [SignPSS], this can also |
| 534 |
// be returned if the size of the salt is too large. |
| 535 |
var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size") |
| 536 |
|
| 537 |
// ErrDecryption represents a failure to decrypt a message. |
| 538 |
// It is deliberately vague to avoid adaptive attacks. |
| 539 |
var ErrDecryption = errors.New("crypto/rsa: decryption error") |
| 540 |
|
| 541 |
// ErrVerification represents a failure to verify a signature. |
| 542 |
// It is deliberately vague to avoid adaptive attacks. |
| 543 |
var ErrVerification = errors.New("crypto/rsa: verification error") |
| 544 |
|
| 545 |
// Precompute performs some calculations that speed up private key operations |
| 546 |
// in the future. It is safe to run on non-validated private keys. |
| 547 |
func (priv *PrivateKey) Precompute() { |
| 548 |
if priv.precomputedIsConsistent() { |
| 549 |
return |
| 550 |
} |
| 551 |
|
| 552 |
precomputed, err := priv.precompute() |
| 553 |
if err != nil { |
| 554 |
// We don't have a way to report errors, so just leave Precomputed.fips |
| 555 |
// nil. Validate will re-run precompute and report its error. |
| 556 |
priv.Precomputed.fips = nil |
| 557 |
return |
| 558 |
} |
| 559 |
priv.Precomputed = precomputed |
| 560 |
} |
| 561 |
|
| 562 |
func (priv *PrivateKey) precompute() (PrecomputedValues, error) { |
| 563 |
var precomputed PrecomputedValues |
| 564 |
|
| 565 |
if priv.N == nil { |
| 566 |
return precomputed, errors.New("crypto/rsa: missing public modulus") |
| 567 |
} |
| 568 |
if priv.D == nil { |
| 569 |
return precomputed, errors.New("crypto/rsa: missing private exponent") |
| 570 |
} |
| 571 |
if len(priv.Primes) != 2 { |
| 572 |
return priv.precomputeLegacy() |
| 573 |
} |
| 574 |
if priv.Primes[0] == nil { |
| 575 |
return precomputed, errors.New("crypto/rsa: prime P is nil") |
| 576 |
} |
| 577 |
if priv.Primes[1] == nil { |
| 578 |
return precomputed, errors.New("crypto/rsa: prime Q is nil") |
| 579 |
} |
| 580 |
|
| 581 |
// If the CRT values are already set, use them. |
| 582 |
if priv.Precomputed.Dp != nil && priv.Precomputed.Dq != nil && priv.Precomputed.Qinv != nil { |
| 583 |
k, err := rsa.NewPrivateKeyWithPrecomputation(priv.N.Bytes(), priv.E, priv.D.Bytes(), |
| 584 |
priv.Primes[0].Bytes(), priv.Primes[1].Bytes(), |
| 585 |
priv.Precomputed.Dp.Bytes(), priv.Precomputed.Dq.Bytes(), priv.Precomputed.Qinv.Bytes()) |
| 586 |
if err != nil { |
| 587 |
return precomputed, err |
| 588 |
} |
| 589 |
precomputed = priv.Precomputed |
| 590 |
precomputed.fips = k |
| 591 |
precomputed.CRTValues = make([]CRTValue, 0) |
| 592 |
return precomputed, nil |
| 593 |
} |
| 594 |
|
| 595 |
k, err := rsa.NewPrivateKey(priv.N.Bytes(), priv.E, priv.D.Bytes(), |
| 596 |
priv.Primes[0].Bytes(), priv.Primes[1].Bytes()) |
| 597 |
if err != nil { |
| 598 |
return precomputed, err |
| 599 |
} |
| 600 |
|
| 601 |
precomputed.fips = k |
| 602 |
_, _, _, _, _, dP, dQ, qInv := k.Export() |
| 603 |
precomputed.Dp = new(big.Int).SetBytes(dP) |
| 604 |
precomputed.Dq = new(big.Int).SetBytes(dQ) |
| 605 |
precomputed.Qinv = new(big.Int).SetBytes(qInv) |
| 606 |
precomputed.CRTValues = make([]CRTValue, 0) |
| 607 |
return precomputed, nil |
| 608 |
} |
| 609 |
|
| 610 |
func (priv *PrivateKey) precomputeLegacy() (PrecomputedValues, error) { |
| 611 |
var precomputed PrecomputedValues |
| 612 |
|
| 613 |
k, err := rsa.NewPrivateKeyWithoutCRT(priv.N.Bytes(), priv.E, priv.D.Bytes()) |
| 614 |
if err != nil { |
| 615 |
return precomputed, err |
| 616 |
} |
| 617 |
precomputed.fips = k |
| 618 |
|
| 619 |
if len(priv.Primes) < 2 { |
| 620 |
return precomputed, nil |
| 621 |
} |
| 622 |
|
| 623 |
// Ensure the Mod and ModInverse calls below don't panic. |
| 624 |
for _, prime := range priv.Primes { |
| 625 |
if prime == nil { |
| 626 |
return precomputed, errors.New("crypto/rsa: prime factor is nil") |
| 627 |
} |
| 628 |
if prime.Cmp(bigOne) <= 0 { |
| 629 |
return precomputed, errors.New("crypto/rsa: prime factor is <= 1") |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne) |
| 634 |
precomputed.Dp.Mod(priv.D, precomputed.Dp) |
| 635 |
|
| 636 |
precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne) |
| 637 |
precomputed.Dq.Mod(priv.D, precomputed.Dq) |
| 638 |
|
| 639 |
precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0]) |
| 640 |
if precomputed.Qinv == nil { |
| 641 |
return precomputed, errors.New("crypto/rsa: prime factors are not relatively prime") |
| 642 |
} |
| 643 |
|
| 644 |
r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1]) |
| 645 |
precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2) |
| 646 |
for i := 2; i < len(priv.Primes); i++ { |
| 647 |
prime := priv.Primes[i] |
| 648 |
values := &precomputed.CRTValues[i-2] |
| 649 |
|
| 650 |
values.Exp = new(big.Int).Sub(prime, bigOne) |
| 651 |
values.Exp.Mod(priv.D, values.Exp) |
| 652 |
|
| 653 |
values.R = new(big.Int).Set(r) |
| 654 |
values.Coeff = new(big.Int).ModInverse(r, prime) |
| 655 |
if values.Coeff == nil { |
| 656 |
return precomputed, errors.New("crypto/rsa: prime factors are not relatively prime") |
| 657 |
} |
| 658 |
|
| 659 |
r.Mul(r, prime) |
| 660 |
} |
| 661 |
|
| 662 |
return precomputed, nil |
| 663 |
} |
| 664 |
|
| 665 |
func fipsPublicKey(pub *PublicKey) (*rsa.PublicKey, error) { |
| 666 |
N, err := bigmod.NewModulus(pub.N.Bytes()) |
| 667 |
if err != nil { |
| 668 |
return nil, err |
| 669 |
} |
| 670 |
return &rsa.PublicKey{N: N, E: pub.E}, nil |
| 671 |
} |
| 672 |
|
| 673 |
func fipsPrivateKey(priv *PrivateKey) (*rsa.PrivateKey, error) { |
| 674 |
if priv.Precomputed.fips != nil { |
| 675 |
return priv.Precomputed.fips, nil |
| 676 |
} |
| 677 |
precomputed, err := priv.precompute() |
| 678 |
if err != nil { |
| 679 |
return nil, err |
| 680 |
} |
| 681 |
return precomputed.fips, nil |
| 682 |
} |