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