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.
14 "crypto/internal/randutil"
17 import "crypto/internal/boring"
19 // This file implements encryption and decryption using PKCS#1 v1.5 padding.
21 // PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using
22 // the crypto.Decrypter interface.
23 type PKCS1v15DecryptOptions struct {
24 // SessionKeyLen is the length of the session key that is being
25 // decrypted. If not zero, then a padding error during decryption will
26 // cause a random plaintext of this length to be returned rather than
27 // an error. These alternatives happen in constant time.
31 // EncryptPKCS1v15 encrypts the given message with RSA and the padding
32 // scheme from PKCS#1 v1.5. The message must be no longer than the
33 // length of the public modulus minus 11 bytes.
35 // The rand parameter is used as a source of entropy to ensure that
36 // encrypting the same message twice doesn't result in the same
39 // WARNING: use of this function to encrypt plaintexts other than
40 // session keys is dangerous. Use RSA OAEP in new protocols.
41 func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error) {
42 randutil.MaybeReadByte(random)
44 if err := checkPub(pub); err != nil {
49 return nil, ErrMessageTooLong
52 if boring.Enabled && random == boring.RandReader {
53 bkey, err := boringPublicKey(pub)
57 return boring.EncryptRSAPKCS1(bkey, msg)
59 boring.UnreachableExceptTests()
61 // EM = 0x00 || 0x02 || PS || 0x00 || M
64 ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):]
65 err := nonZeroRandomBytes(ps, random)
69 em[len(em)-len(msg)-1] = 0
73 var bkey *boring.PublicKeyRSA
74 bkey, err = boringPublicKey(pub)
78 return boring.EncryptRSANoPadding(bkey, em)
81 m := new(big.Int).SetBytes(em)
82 c := encrypt(new(big.Int), pub, m)
83 copyWithLeftPad(em, c.Bytes())
87 // DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5.
88 // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
90 // Note that whether this function returns an error or not discloses secret
91 // information. If an attacker can cause this function to run repeatedly and
92 // learn whether each instance returned an error then they can decrypt and
93 // forge signatures as if they had the private key. See
94 // DecryptPKCS1v15SessionKey for a way of solving this problem.
95 func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error) {
96 if err := checkPub(&priv.PublicKey); err != nil {
101 bkey, err := boringPrivateKey(priv)
105 out, err := boring.DecryptRSAPKCS1(bkey, ciphertext)
107 return nil, ErrDecryption
112 valid, out, index, err := decryptPKCS1v15(rand, priv, ciphertext)
117 return nil, ErrDecryption
119 return out[index:], nil
122 // DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5.
123 // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
124 // It returns an error if the ciphertext is the wrong length or if the
125 // ciphertext is greater than the public modulus. Otherwise, no error is
126 // returned. If the padding is valid, the resulting plaintext message is copied
127 // into key. Otherwise, key is unchanged. These alternatives occur in constant
128 // time. It is intended that the user of this function generate a random
129 // session key beforehand and continue the protocol with the resulting value.
130 // This will remove any possibility that an attacker can learn any information
131 // about the plaintext.
132 // See ``Chosen Ciphertext Attacks Against Protocols Based on the RSA
133 // Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology
136 // Note that if the session key is too small then it may be possible for an
137 // attacker to brute-force it. If they can do that then they can learn whether
138 // a random value was used (because it'll be different for the same ciphertext)
139 // and thus whether the padding was correct. This defeats the point of this
140 // function. Using at least a 16-byte key will protect against this attack.
141 func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error {
142 if err := checkPub(&priv.PublicKey); err != nil {
146 if k-(len(key)+3+8) < 0 {
150 valid, em, index, err := decryptPKCS1v15(rand, priv, ciphertext)
156 // This should be impossible because decryptPKCS1v15 always
157 // returns the full slice.
161 valid &= subtle.ConstantTimeEq(int32(len(em)-index), int32(len(key)))
162 subtle.ConstantTimeCopy(valid, key, em[len(em)-len(key):])
166 // decryptPKCS1v15 decrypts ciphertext using priv and blinds the operation if
167 // rand is not nil. It returns one or zero in valid that indicates whether the
168 // plaintext was correctly structured. In either case, the plaintext is
169 // returned in em so that it may be read independently of whether it was valid
170 // in order to maintain constant memory access patterns. If the plaintext was
171 // valid then index contains the index of the original message in em.
172 func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error) {
180 var bkey *boring.PrivateKeyRSA
181 bkey, err = boringPrivateKey(priv)
185 em, err = boring.DecryptRSANoPadding(bkey, ciphertext)
190 c := new(big.Int).SetBytes(ciphertext)
192 m, err = decrypt(rand, priv, c)
196 em = leftPad(m.Bytes(), k)
199 firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
200 secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2)
202 // The remainder of the plaintext must be a string of non-zero random
203 // octets, followed by a 0, followed by the message.
204 // lookingForIndex: 1 iff we are still looking for the zero.
205 // index: the offset of the first zero byte.
208 for i := 2; i < len(em); i++ {
209 equals0 := subtle.ConstantTimeByteEq(em[i], 0)
210 index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index)
211 lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex)
214 // The PS padding must be at least 8 bytes long, and it starts two
216 validPS := subtle.ConstantTimeLessOrEq(2+8, index)
218 valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1) & validPS
219 index = subtle.ConstantTimeSelect(valid, index+1, 0)
220 return valid, em, index, nil
223 // nonZeroRandomBytes fills the given slice with non-zero random octets.
224 func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
225 _, err = io.ReadFull(rand, s)
230 for i := 0; i < len(s); i++ {
232 _, err = io.ReadFull(rand, s[i:i+1])
236 // In tests, the PRNG may return all zeros so we do
237 // this to break the loop.
245 // These are ASN1 DER structures:
246 // DigestInfo ::= SEQUENCE {
247 // digestAlgorithm AlgorithmIdentifier,
248 // digest OCTET STRING
250 // For performance, we don't use the generic ASN1 encoder. Rather, we
251 // precompute a prefix of the digest value that makes a valid ASN1 DER string
252 // with the correct contents.
253 var hashPrefixes = map[crypto.Hash][]byte{
254 crypto.MD5: {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
255 crypto.SHA1: {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14},
256 crypto.SHA224: {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
257 crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
258 crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
259 crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
260 crypto.MD5SHA1: {}, // A special TLS case which doesn't use an ASN1 prefix.
261 crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14},
264 // SignPKCS1v15 calculates the signature of hashed using
265 // RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. Note that hashed must
266 // be the result of hashing the input message using the given hash
267 // function. If hash is zero, hashed is signed directly. This isn't
268 // advisable except for interoperability.
270 // If rand is not nil then RSA blinding will be used to avoid timing
271 // side-channel attacks.
273 // This function is deterministic. Thus, if the set of possible
274 // messages is small, an attacker may be able to build a map from
275 // messages to signatures and identify the signed messages. As ever,
276 // signatures provide authenticity, not confidentiality.
277 func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
278 hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
283 tLen := len(prefix) + hashLen
286 return nil, ErrMessageTooLong
290 bkey, err := boringPrivateKey(priv)
294 return boring.SignRSAPKCS1v15(bkey, hash, hashed)
297 // EM = 0x00 || 0x01 || PS || 0x00 || T
298 em := make([]byte, k)
300 for i := 2; i < k-tLen-1; i++ {
303 copy(em[k-tLen:k-hashLen], prefix)
304 copy(em[k-hashLen:k], hashed)
306 m := new(big.Int).SetBytes(em)
307 c, err := decryptAndCheck(random, priv, m)
312 copyWithLeftPad(em, c.Bytes())
316 // VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature.
317 // hashed is the result of hashing the input message using the given hash
318 // function and sig is the signature. A valid signature is indicated by
319 // returning a nil error. If hash is zero then hashed is used directly. This
320 // isn't advisable except for interoperability.
321 func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
323 bkey, err := boringPublicKey(pub)
327 if err := boring.VerifyRSAPKCS1v15(bkey, hash, hashed, sig); err != nil {
328 return ErrVerification
333 hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
338 tLen := len(prefix) + hashLen
341 return ErrVerification
344 // RFC 8017 Section 8.2.2: If the length of the signature S is not k
345 // octets (where k is the length in octets of the RSA modulus n), output
346 // "invalid signature" and stop.
348 return ErrVerification
351 c := new(big.Int).SetBytes(sig)
352 m := encrypt(new(big.Int), pub, c)
353 em := leftPad(m.Bytes(), k)
354 // EM = 0x00 || 0x01 || PS || 0x00 || T
356 ok := subtle.ConstantTimeByteEq(em[0], 0)
357 ok &= subtle.ConstantTimeByteEq(em[1], 1)
358 ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed)
359 ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix)
360 ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0)
362 for i := 2; i < k-tLen-1; i++ {
363 ok &= subtle.ConstantTimeByteEq(em[i], 0xff)
367 return ErrVerification
373 func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) {
374 // Special case: crypto.Hash(0) is used to indicate that the data is
377 return inLen, nil, nil
380 hashLen = hash.Size()
381 if inLen != hashLen {
382 return 0, nil, errors.New("crypto/rsa: input must be hashed message")
384 prefix, ok := hashPrefixes[hash]
386 return 0, nil, errors.New("crypto/rsa: unsupported hash function")
391 // copyWithLeftPad copies src to the end of dest, padding with zero bytes as
393 func copyWithLeftPad(dest, src []byte) {
394 numPaddingBytes := len(dest) - len(src)
395 for i := 0; i < numPaddingBytes; i++ {
398 copy(dest[numPaddingBytes:], src)