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.
5 // Package rsa implements RSA encryption as specified in PKCS#1 and RFC 8017.
7 // RSA is a single, fundamental operation that is used in this package to
8 // implement either public-key encryption or public-key signatures.
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
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.
22 // The RSA operations in this package are not implemented using constant-time algorithms.
35 "crypto/internal/randutil"
39 "crypto/internal/boring"
43 var bigZero = big.NewInt(0)
44 var bigOne = big.NewInt(1)
46 // A PublicKey represents the public part of an RSA key.
47 type PublicKey struct {
49 E int // public exponent
54 // Size returns the modulus size in bytes. Raw signatures and ciphertexts
55 // for or by this public key will have the same size.
56 func (pub *PublicKey) Size() int {
57 return (pub.N.BitLen() + 7) / 8
60 // Equal reports whether pub and x have the same value.
61 func (pub *PublicKey) Equal(x crypto.PublicKey) bool {
62 xx, ok := x.(*PublicKey)
66 return pub.N.Cmp(xx.N) == 0 && pub.E == xx.E
69 // OAEPOptions is an interface for passing options to OAEP decryption using the
70 // crypto.Decrypter interface.
71 type OAEPOptions struct {
72 // Hash is the hash function that will be used when generating the mask.
74 // Label is an arbitrary byte string that must be equal to the value
75 // used when encrypting.
80 errPublicModulus = errors.New("crypto/rsa: missing public modulus")
81 errPublicExponentSmall = errors.New("crypto/rsa: public exponent too small")
82 errPublicExponentLarge = errors.New("crypto/rsa: public exponent too large")
85 // checkPub sanity checks the public key before we use it.
86 // We require pub.E to fit into a 32-bit integer so that we
87 // do not have different behavior depending on whether
88 // int is 32 or 64 bits. See also
89 // https://www.imperialviolet.org/2012/03/16/rsae.html.
90 func checkPub(pub *PublicKey) error {
92 return errPublicModulus
95 return errPublicExponentSmall
98 return errPublicExponentLarge
103 // A PrivateKey represents an RSA key
104 type PrivateKey struct {
105 PublicKey // public part.
106 D *big.Int // private exponent
107 Primes []*big.Int // prime factors of N, has >= 2 elements.
109 // Precomputed contains precomputed values that speed up private
110 // operations, if available.
111 Precomputed PrecomputedValues
113 boring unsafe.Pointer
116 // Public returns the public key corresponding to priv.
117 func (priv *PrivateKey) Public() crypto.PublicKey {
118 return &priv.PublicKey
121 // Sign signs digest with priv, reading randomness from rand. If opts is a
122 // *PSSOptions then the PSS algorithm will be used, otherwise PKCS#1 v1.5 will
123 // be used. digest must be the result of hashing the input message using
126 // This method implements crypto.Signer, which is an interface to support keys
127 // where the private part is kept in, for example, a hardware module. Common
128 // uses should use the Sign* functions in this package directly.
129 func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
130 if pssOpts, ok := opts.(*PSSOptions); ok {
131 return SignPSS(rand, priv, pssOpts.Hash, digest, pssOpts)
134 return SignPKCS1v15(rand, priv, opts.HashFunc(), digest)
137 // Decrypt decrypts ciphertext with priv. If opts is nil or of type
138 // *PKCS1v15DecryptOptions then PKCS#1 v1.5 decryption is performed. Otherwise
139 // opts must have type *OAEPOptions and OAEP decryption is done.
140 func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
142 return DecryptPKCS1v15(rand, priv, ciphertext)
145 switch opts := opts.(type) {
147 return DecryptOAEP(opts.Hash.New(), rand, priv, ciphertext, opts.Label)
149 case *PKCS1v15DecryptOptions:
150 if l := opts.SessionKeyLen; l > 0 {
151 plaintext = make([]byte, l)
152 if _, err := io.ReadFull(rand, plaintext); err != nil {
155 if err := DecryptPKCS1v15SessionKey(rand, priv, ciphertext, plaintext); err != nil {
158 return plaintext, nil
160 return DecryptPKCS1v15(rand, priv, ciphertext)
164 return nil, errors.New("crypto/rsa: invalid options for Decrypt")
168 type PrecomputedValues struct {
169 Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
170 Qinv *big.Int // Q^-1 mod P
172 // CRTValues is used for the 3rd and subsequent primes. Due to a
173 // historical accident, the CRT for the first two primes is handled
174 // differently in PKCS#1 and interoperability is sufficiently
175 // important that we mirror this.
179 // CRTValue contains the precomputed Chinese remainder theorem values.
180 type CRTValue struct {
181 Exp *big.Int // D mod (prime-1).
182 Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
183 R *big.Int // product of primes prior to this (inc p and q).
186 // Validate performs basic sanity checks on the key.
187 // It returns nil if the key is valid, or else an error describing a problem.
188 func (priv *PrivateKey) Validate() error {
189 if err := checkPub(&priv.PublicKey); err != nil {
193 // Check that Πprimes == n.
194 modulus := new(big.Int).Set(bigOne)
195 for _, prime := range priv.Primes {
196 // Any primes ≤ 1 will cause divide-by-zero panics later.
197 if prime.Cmp(bigOne) <= 0 {
198 return errors.New("crypto/rsa: invalid prime value")
200 modulus.Mul(modulus, prime)
202 if modulus.Cmp(priv.N) != 0 {
203 return errors.New("crypto/rsa: invalid modulus")
206 // Check that de ≡ 1 mod p-1, for each prime.
207 // This implies that e is coprime to each p-1 as e has a multiplicative
208 // inverse. Therefore e is coprime to lcm(p-1,q-1,r-1,...) =
209 // exponent(ℤ/nℤ). It also implies that a^de ≡ a mod p as a^(p-1) ≡ 1
210 // mod p. Thus a^de ≡ a mod n for all a coprime to n, as required.
211 congruence := new(big.Int)
212 de := new(big.Int).SetInt64(int64(priv.E))
214 for _, prime := range priv.Primes {
215 pminus1 := new(big.Int).Sub(prime, bigOne)
216 congruence.Mod(de, pminus1)
217 if congruence.Cmp(bigOne) != 0 {
218 return errors.New("crypto/rsa: invalid exponents")
224 // GenerateKey generates an RSA keypair of the given bit size using the
225 // random source random (for example, crypto/rand.Reader).
226 func GenerateKey(random io.Reader, bits int) (*PrivateKey, error) {
227 return GenerateMultiPrimeKey(random, 2, bits)
230 // GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit
231 // size and the given random source, as suggested in [1]. Although the public
232 // keys are compatible (actually, indistinguishable) from the 2-prime case,
233 // the private keys are not. Thus it may not be possible to export multi-prime
234 // private keys in certain formats or to subsequently import them into other
237 // Table 1 in [2] suggests maximum numbers of primes for a given size.
239 // [1] US patent 4405829 (1972, expired)
240 // [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
241 func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error) {
242 randutil.MaybeReadByte(random)
244 if boring.Enabled && random == boring.RandReader && nprimes == 2 && (bits == 2048 || bits == 3072) {
245 N, E, D, P, Q, Dp, Dq, Qinv, err := boring.GenerateKeyRSA(bits)
250 if !E.IsInt64() || int64(int(e64)) != e64 {
251 return nil, errors.New("crypto/rsa: generated key exponent too large")
254 PublicKey: PublicKey{
259 Primes: []*big.Int{P, Q},
260 Precomputed: PrecomputedValues{
264 CRTValues: make([]CRTValue, 0), // non-nil, to match Precompute
270 priv := new(PrivateKey)
274 return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2")
278 primeLimit := float64(uint64(1) << uint(bits/nprimes))
279 // pi approximates the number of primes less than primeLimit
280 pi := primeLimit / (math.Log(primeLimit) - 1)
281 // Generated primes start with 11 (in binary) so we can only
282 // use a quarter of them.
284 // Use a factor of two to ensure that key generation terminates
285 // in a reasonable amount of time.
287 if pi <= float64(nprimes) {
288 return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key")
292 primes := make([]*big.Int, nprimes)
297 // crypto/rand should set the top two bits in each prime.
298 // Thus each prime has the form
299 // p_i = 2^bitlen(p_i) × 0.11... (in base 2).
300 // And the product is:
302 // where α is the product of nprimes numbers of the form 0.11...
304 // If α < 1/2 (which can happen for nprimes > 2), we need to
305 // shift todo to compensate for lost bits: the mean value of 0.11...
306 // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2
307 // will give good results.
309 todo += (nprimes - 2) / 5
311 for i := 0; i < nprimes; i++ {
313 primes[i], err = rand.Prime(random, todo/(nprimes-i))
317 todo -= primes[i].BitLen()
320 // Make sure that primes is pairwise unequal.
321 for i, prime := range primes {
322 for j := 0; j < i; j++ {
323 if prime.Cmp(primes[j]) == 0 {
324 continue NextSetOfPrimes
329 n := new(big.Int).Set(bigOne)
330 totient := new(big.Int).Set(bigOne)
331 pminus1 := new(big.Int)
332 for _, prime := range primes {
334 pminus1.Sub(prime, bigOne)
335 totient.Mul(totient, pminus1)
337 if n.BitLen() != bits {
338 // This should never happen for nprimes == 2 because
339 // crypto/rand should set the top two bits in each prime.
340 // For nprimes > 2 we hope it does not happen often.
341 continue NextSetOfPrimes
344 priv.D = new(big.Int)
345 e := big.NewInt(int64(priv.E))
346 ok := priv.D.ModInverse(e, totient)
359 // incCounter increments a four byte, big-endian counter.
360 func incCounter(c *[4]byte) {
361 if c[3]++; c[3] != 0 {
364 if c[2]++; c[2] != 0 {
367 if c[1]++; c[1] != 0 {
373 // mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function
374 // specified in PKCS#1 v2.1.
375 func mgf1XOR(out []byte, hash hash.Hash, seed []byte) {
380 for done < len(out) {
382 hash.Write(counter[0:4])
383 digest = hash.Sum(digest[:0])
386 for i := 0; i < len(digest) && done < len(out); i++ {
387 out[done] ^= digest[i]
394 // ErrMessageTooLong is returned when attempting to encrypt a message which is
395 // too large for the size of the public key.
396 var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size")
398 func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int {
400 e := big.NewInt(int64(pub.E))
405 // EncryptOAEP encrypts the given message with RSA-OAEP.
407 // OAEP is parameterised by a hash function that is used as a random oracle.
408 // Encryption and decryption of a given message must use the same hash function
409 // and sha256.New() is a reasonable choice.
411 // The random parameter is used as a source of entropy to ensure that
412 // encrypting the same message twice doesn't result in the same ciphertext.
414 // The label parameter may contain arbitrary data that will not be encrypted,
415 // but which gives important context to the message. For example, if a given
416 // public key is used to decrypt two types of messages then distinct label
417 // values could be used to ensure that a ciphertext for one purpose cannot be
418 // used for another by an attacker. If not required it can be empty.
420 // The message must be no longer than the length of the public modulus minus
421 // twice the hash length, minus a further 2.
422 func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error) {
423 if err := checkPub(pub); err != nil {
428 if len(msg) > k-2*hash.Size()-2 {
429 return nil, ErrMessageTooLong
432 if boring.Enabled && random == boring.RandReader {
433 bkey, err := boringPublicKey(pub)
437 return boring.EncryptRSAOAEP(hash, bkey, msg, label)
439 boring.UnreachableExceptTests()
442 lHash := hash.Sum(nil)
445 em := make([]byte, k)
446 seed := em[1 : 1+hash.Size()]
447 db := em[1+hash.Size():]
449 copy(db[0:hash.Size()], lHash)
450 db[len(db)-len(msg)-1] = 1
451 copy(db[len(db)-len(msg):], msg)
453 _, err := io.ReadFull(random, seed)
458 mgf1XOR(db, hash, seed)
459 mgf1XOR(seed, hash, db)
462 var bkey *boring.PublicKeyRSA
463 bkey, err = boringPublicKey(pub)
467 return boring.EncryptRSANoPadding(bkey, em)
472 c := encrypt(new(big.Int), pub, m)
474 out := make([]byte, k)
475 return c.FillBytes(out), nil
478 // ErrDecryption represents a failure to decrypt a message.
479 // It is deliberately vague to avoid adaptive attacks.
480 var ErrDecryption = errors.New("crypto/rsa: decryption error")
482 // ErrVerification represents a failure to verify a signature.
483 // It is deliberately vague to avoid adaptive attacks.
484 var ErrVerification = errors.New("crypto/rsa: verification error")
486 // Precompute performs some calculations that speed up private key operations
488 func (priv *PrivateKey) Precompute() {
489 if priv.Precomputed.Dp != nil {
493 priv.Precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
494 priv.Precomputed.Dp.Mod(priv.D, priv.Precomputed.Dp)
496 priv.Precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
497 priv.Precomputed.Dq.Mod(priv.D, priv.Precomputed.Dq)
499 priv.Precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])
501 r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])
502 priv.Precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2)
503 for i := 2; i < len(priv.Primes); i++ {
504 prime := priv.Primes[i]
505 values := &priv.Precomputed.CRTValues[i-2]
507 values.Exp = new(big.Int).Sub(prime, bigOne)
508 values.Exp.Mod(priv.D, values.Exp)
510 values.R = new(big.Int).Set(r)
511 values.Coeff = new(big.Int).ModInverse(r, prime)
517 // decrypt performs an RSA decryption, resulting in a plaintext integer. If a
518 // random source is given, RSA blinding is used.
519 func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) {
520 if len(priv.Primes) <= 2 {
523 // TODO(agl): can we get away with reusing blinds?
524 if c.Cmp(priv.N) > 0 {
528 if priv.N.Sign() == 0 {
529 return nil, ErrDecryption
534 randutil.MaybeReadByte(random)
536 // Blinding enabled. Blinding involves multiplying c by r^e.
537 // Then the decryption operation performs (m^e * r^e)^d mod n
538 // which equals mr mod n. The factor of r can then be removed
539 // by multiplying by the multiplicative inverse of r.
544 r, err = rand.Int(random, priv.N)
548 if r.Cmp(bigZero) == 0 {
551 ok := ir.ModInverse(r, priv.N)
556 bigE := big.NewInt(int64(priv.E))
557 rpowe := new(big.Int).Exp(r, bigE, priv.N) // N != 0
558 cCopy := new(big.Int).Set(c)
559 cCopy.Mul(cCopy, rpowe)
560 cCopy.Mod(cCopy, priv.N)
564 if priv.Precomputed.Dp == nil {
565 m = new(big.Int).Exp(c, priv.D, priv.N)
567 // We have the precalculated values needed for the CRT.
568 m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0])
569 m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1])
572 m.Add(m, priv.Primes[0])
574 m.Mul(m, priv.Precomputed.Qinv)
575 m.Mod(m, priv.Primes[0])
576 m.Mul(m, priv.Primes[1])
579 for i, values := range priv.Precomputed.CRTValues {
580 prime := priv.Primes[2+i]
581 m2.Exp(c, values.Exp, prime)
583 m2.Mul(m2, values.Coeff)
602 func decryptAndCheck(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) {
603 m, err = decrypt(random, priv, c)
608 // In order to defend against errors in the CRT computation, m^e is
609 // calculated, which should match the original ciphertext.
610 check := encrypt(new(big.Int), &priv.PublicKey, m)
611 if c.Cmp(check) != 0 {
612 return nil, errors.New("rsa: internal error")
617 // DecryptOAEP decrypts ciphertext using RSA-OAEP.
619 // OAEP is parameterised by a hash function that is used as a random oracle.
620 // Encryption and decryption of a given message must use the same hash function
621 // and sha256.New() is a reasonable choice.
623 // The random parameter, if not nil, is used to blind the private-key operation
624 // and avoid timing side-channel attacks. Blinding is purely internal to this
625 // function – the random data need not match that used when encrypting.
627 // The label parameter must match the value given when encrypting. See
628 // EncryptOAEP for details.
629 func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error) {
630 if err := checkPub(&priv.PublicKey); err != nil {
634 if len(ciphertext) > k ||
635 k < hash.Size()*2+2 {
636 return nil, ErrDecryption
640 bkey, err := boringPrivateKey(priv)
644 out, err := boring.DecryptRSAOAEP(hash, bkey, ciphertext, label)
646 return nil, ErrDecryption
650 c := new(big.Int).SetBytes(ciphertext)
652 m, err := decrypt(random, priv, c)
658 lHash := hash.Sum(nil)
661 // We probably leak the number of leading zeros.
662 // It's not clear that we can do anything about this.
663 em := m.FillBytes(make([]byte, k))
665 firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
667 seed := em[1 : hash.Size()+1]
668 db := em[hash.Size()+1:]
670 mgf1XOR(seed, hash, db)
671 mgf1XOR(db, hash, seed)
673 lHash2 := db[0:hash.Size()]
675 // We have to validate the plaintext in constant time in order to avoid
676 // attacks like: J. Manger. A Chosen Ciphertext Attack on RSA Optimal
677 // Asymmetric Encryption Padding (OAEP) as Standardized in PKCS #1
678 // v2.0. In J. Kilian, editor, Advances in Cryptology.
679 lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2)
681 // The remainder of the plaintext must be zero or more 0x00, followed
682 // by 0x01, followed by the message.
683 // lookingForIndex: 1 iff we are still looking for the 0x01
684 // index: the offset of the first 0x01 byte
685 // invalid: 1 iff we saw a non-zero byte before the 0x01.
686 var lookingForIndex, index, invalid int
688 rest := db[hash.Size():]
690 for i := 0; i < len(rest); i++ {
691 equals0 := subtle.ConstantTimeByteEq(rest[i], 0)
692 equals1 := subtle.ConstantTimeByteEq(rest[i], 1)
693 index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index)
694 lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex)
695 invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid)
698 if firstByteIsZero&lHash2Good&^invalid&^lookingForIndex != 1 {
699 return nil, ErrDecryption
702 return rest[index+1:], nil