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 // This package implements RSA encryption as specified in PKCS#1.
8 // TODO(agl): Add support for PSS padding.
18 var bigZero
= big
.NewInt(0)
19 var bigOne
= big
.NewInt(1)
21 // randomPrime returns a number, p, of the given size, such that p is prime
22 // with high probability.
23 func randomPrime(rand io
.Reader
, bits
int) (p
*big
.Int
, err os
.Error
) {
28 bytes
:= make([]byte, (bits
+7)/8)
32 _
, err
= io
.ReadFull(rand
, bytes
)
37 // Don't let the value be too small.
39 // Make the value odd since an even number this large certainly isn't prime.
40 bytes
[len(bytes
)-1] |
= 1
43 if big
.ProbablyPrime(p
, 20) {
51 // randomNumber returns a uniform random value in [0, max).
52 func randomNumber(rand io
.Reader
, max
*big
.Int
) (n
*big
.Int
, err os
.Error
) {
53 k
:= (max
.BitLen() + 7) / 8
55 // r is the number of bits in the used in the most significant byte of
57 r
:= uint(max
.BitLen() % 8)
62 bytes
:= make([]byte, k
)
66 _
, err
= io
.ReadFull(rand
, bytes
)
71 // Clear bits in the first byte to increase the probability
72 // that the candidate is < max.
73 bytes
[0] &= uint8(int(1<<r
) - 1)
84 // A PublicKey represents the public part of an RSA key.
85 type PublicKey
struct {
87 E
int // public exponent
90 // A PrivateKey represents an RSA key
91 type PrivateKey
struct {
92 PublicKey
// public part.
93 D
*big
.Int
// private exponent
94 P
, Q
*big
.Int
// prime factors of N
97 // Validate performs basic sanity checks on the key.
98 // It returns nil if the key is valid, or else an os.Error describing a problem.
100 func (priv PrivateKey
) Validate() os
.Error
{
101 // Check that p and q are prime. Note that this is just a sanity
102 // check. Since the random witnesses chosen by ProbablyPrime are
103 // deterministic, given the candidate number, it's easy for an attack
104 // to generate composites that pass this test.
105 if !big
.ProbablyPrime(priv
.P
, 20) {
106 return os
.ErrorString("P is composite")
108 if !big
.ProbablyPrime(priv
.Q
, 20) {
109 return os
.ErrorString("Q is composite")
112 // Check that p*q == n.
113 modulus
:= new(big
.Int
).Mul(priv
.P
, priv
.Q
)
114 if modulus
.Cmp(priv
.N
) != 0 {
115 return os
.ErrorString("invalid modulus")
117 // Check that e and totient(p, q) are coprime.
118 pminus1
:= new(big
.Int
).Sub(priv
.P
, bigOne
)
119 qminus1
:= new(big
.Int
).Sub(priv
.Q
, bigOne
)
120 totient
:= new(big
.Int
).Mul(pminus1
, qminus1
)
121 e
:= big
.NewInt(int64(priv
.E
))
125 big
.GcdInt(gcd
, x
, y
, totient
, e
)
126 if gcd
.Cmp(bigOne
) != 0 {
127 return os
.ErrorString("invalid public exponent E")
129 // Check that de ≡ 1 (mod totient(p, q))
130 de
:= new(big
.Int
).Mul(priv
.D
, e
)
132 if de
.Cmp(bigOne
) != 0 {
133 return os
.ErrorString("invalid private exponent D")
138 // GenerateKeyPair generates an RSA keypair of the given bit size.
139 func GenerateKey(rand io
.Reader
, bits
int) (priv
*PrivateKey
, err os
.Error
) {
140 priv
= new(PrivateKey
)
141 // Smaller public exponents lead to faster public key
142 // operations. Since the exponent must be coprime to
143 // (p-1)(q-1), the smallest possible value is 3. Some have
144 // suggested that a larger exponent (often 2**16+1) be used
145 // since previous implementation bugs[1] were avoided when this
146 // was the case. However, there are no current reasons not to use
148 // [1] http://marc.info/?l=cryptography&m=115694833312008&w=2
151 pminus1
:= new(big
.Int
)
152 qminus1
:= new(big
.Int
)
153 totient
:= new(big
.Int
)
156 p
, err
:= randomPrime(rand
, bits
/2)
161 q
, err
:= randomPrime(rand
, bits
/2)
170 n
:= new(big
.Int
).Mul(p
, q
)
171 pminus1
.Sub(p
, bigOne
)
172 qminus1
.Sub(q
, bigOne
)
173 totient
.Mul(pminus1
, qminus1
)
176 priv
.D
= new(big
.Int
)
178 e
:= big
.NewInt(int64(priv
.E
))
179 big
.GcdInt(g
, priv
.D
, y
, e
, totient
)
181 if g
.Cmp(bigOne
) == 0 {
182 priv
.D
.Add(priv
.D
, totient
)
194 // incCounter increments a four byte, big-endian counter.
195 func incCounter(c
*[4]byte) {
196 if c
[3]++; c
[3] != 0 {
199 if c
[2]++; c
[2] != 0 {
202 if c
[1]++; c
[1] != 0 {
208 // mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function
209 // specified in PKCS#1 v2.1.
210 func mgf1XOR(out
[]byte, hash hash
.Hash
, seed
[]byte) {
214 for done
< len(out
) {
216 hash
.Write(counter
[0:4])
220 for i
:= 0; i
< len(digest
) && done
< len(out
); i
++ {
221 out
[done
] ^= digest
[i
]
228 // MessageTooLongError is returned when attempting to encrypt a message which
229 // is too large for the size of the public key.
230 type MessageTooLongError
struct{}
232 func (MessageTooLongError
) String() string {
233 return "message too long for RSA public key size"
236 func encrypt(c
*big
.Int
, pub
*PublicKey
, m
*big
.Int
) *big
.Int
{
237 e
:= big
.NewInt(int64(pub
.E
))
242 // EncryptOAEP encrypts the given message with RSA-OAEP.
243 // The message must be no longer than the length of the public modulus less
244 // twice the hash length plus 2.
245 func EncryptOAEP(hash hash
.Hash
, rand io
.Reader
, pub
*PublicKey
, msg
[]byte, label
[]byte) (out
[]byte, err os
.Error
) {
247 k
:= (pub
.N
.BitLen() + 7) / 8
248 if len(msg
) > k
-2*hash
.Size()-2 {
249 err
= MessageTooLongError
{}
257 em
:= make([]byte, k
)
258 seed
:= em
[1 : 1+hash
.Size()]
259 db
:= em
[1+hash
.Size():]
261 copy(db
[0:hash
.Size()], lHash
)
262 db
[len(db
)-len(msg
)-1] = 1
263 copy(db
[len(db
)-len(msg
):], msg
)
265 _
, err
= io
.ReadFull(rand
, seed
)
270 mgf1XOR(db
, hash
, seed
)
271 mgf1XOR(seed
, hash
, db
)
275 c
:= encrypt(new(big
.Int
), pub
, m
)
280 // A DecryptionError represents a failure to decrypt a message.
281 // It is deliberately vague to avoid adaptive attacks.
282 type DecryptionError
struct{}
284 func (DecryptionError
) String() string { return "RSA decryption error" }
286 // A VerificationError represents a failure to verify a signature.
287 // It is deliberately vague to avoid adaptive attacks.
288 type VerificationError
struct{}
290 func (VerificationError
) String() string { return "RSA verification error" }
292 // modInverse returns ia, the inverse of a in the multiplicative group of prime
293 // order n. It requires that a be a member of the group (i.e. less than n).
294 func modInverse(a
, n
*big
.Int
) (ia
*big
.Int
, ok
bool) {
298 big
.GcdInt(g
, x
, y
, a
, n
)
299 if g
.Cmp(bigOne
) != 0 {
300 // In this case, a and n aren't coprime and we cannot calculate
301 // the inverse. This happens because the values of n are nearly
302 // prime (being the product of two primes) rather than truly
307 if x
.Cmp(bigOne
) < 0 {
308 // 0 is not the multiplicative inverse of any element so, if x
309 // < 1, then x is negative.
316 // decrypt performs an RSA decryption, resulting in a plaintext integer. If a
317 // random source is given, RSA blinding is used.
318 func decrypt(rand io
.Reader
, priv
*PrivateKey
, c
*big
.Int
) (m
*big
.Int
, err os
.Error
) {
319 // TODO(agl): can we get away with reusing blinds?
320 if c
.Cmp(priv
.N
) > 0 {
321 err
= DecryptionError
{}
327 // Blinding enabled. Blinding involves multiplying c by r^e.
328 // Then the decryption operation performs (m^e * r^e)^d mod n
329 // which equals mr mod n. The factor of r can then be removed
330 // by multipling by the multiplicative inverse of r.
335 r
, err
= randomNumber(rand
, priv
.N
)
339 if r
.Cmp(bigZero
) == 0 {
343 ir
, ok
= modInverse(r
, priv
.N
)
348 bigE
:= big
.NewInt(int64(priv
.E
))
349 rpowe
:= new(big
.Int
).Exp(r
, bigE
, priv
.N
)
354 m
= new(big
.Int
).Exp(c
, priv
.D
, priv
.N
)
365 // DecryptOAEP decrypts ciphertext using RSA-OAEP.
366 // If rand != nil, DecryptOAEP uses RSA blinding to avoid timing side-channel attacks.
367 func DecryptOAEP(hash hash
.Hash
, rand io
.Reader
, priv
*PrivateKey
, ciphertext
[]byte, label
[]byte) (msg
[]byte, err os
.Error
) {
368 k
:= (priv
.N
.BitLen() + 7) / 8
369 if len(ciphertext
) > k ||
370 k
< hash
.Size()*2+2 {
371 err
= DecryptionError
{}
375 c
:= new(big
.Int
).SetBytes(ciphertext
)
377 m
, err
:= decrypt(rand
, priv
, c
)
386 // Converting the plaintext number to bytes will strip any
387 // leading zeros so we may have to left pad. We do this unconditionally
388 // to avoid leaking timing information. (Although we still probably
389 // leak the number of leading zeros. It's not clear that we can do
390 // anything about this.)
391 em
:= leftPad(m
.Bytes(), k
)
393 firstByteIsZero
:= subtle
.ConstantTimeByteEq(em
[0], 0)
395 seed
:= em
[1 : hash
.Size()+1]
396 db
:= em
[hash
.Size()+1:]
398 mgf1XOR(seed
, hash
, db
)
399 mgf1XOR(db
, hash
, seed
)
401 lHash2
:= db
[0:hash
.Size()]
403 // We have to validate the plaintext in constant time in order to avoid
404 // attacks like: J. Manger. A Chosen Ciphertext Attack on RSA Optimal
405 // Asymmetric Encryption Padding (OAEP) as Standardized in PKCS #1
406 // v2.0. In J. Kilian, editor, Advances in Cryptology.
407 lHash2Good
:= subtle
.ConstantTimeCompare(lHash
, lHash2
)
409 // The remainder of the plaintext must be zero or more 0x00, followed
410 // by 0x01, followed by the message.
411 // lookingForIndex: 1 iff we are still looking for the 0x01
412 // index: the offset of the first 0x01 byte
413 // invalid: 1 iff we saw a non-zero byte before the 0x01.
414 var lookingForIndex
, index
, invalid
int
416 rest
:= db
[hash
.Size():]
418 for i
:= 0; i
< len(rest
); i
++ {
419 equals0
:= subtle
.ConstantTimeByteEq(rest
[i
], 0)
420 equals1
:= subtle
.ConstantTimeByteEq(rest
[i
], 1)
421 index
= subtle
.ConstantTimeSelect(lookingForIndex
&equals1
, i
, index
)
422 lookingForIndex
= subtle
.ConstantTimeSelect(equals1
, 0, lookingForIndex
)
423 invalid
= subtle
.ConstantTimeSelect(lookingForIndex
&^equals0
, 1, invalid
)
426 if firstByteIsZero
&lHash2Good
&^invalid
&^lookingForIndex
!= 1 {
427 err
= DecryptionError
{}
435 // leftPad returns a new slice of length size. The contents of input are right
436 // aligned in the new slice.
437 func leftPad(input
[]byte, size
int) (out
[]byte) {
442 out
= make([]byte, size
)
443 copy(out
[len(out
)-n
:], input
)