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