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.
9 "crypto/internal/boring"
16 // This file implements encryption and decryption using PKCS#1 v1.5 padding.
18 // PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using
19 // the crypto.Decrypter interface.
20 type PKCS1v15DecryptOptions struct {
21 // SessionKeyLen is the length of the session key that is being
22 // decrypted. If not zero, then a padding error during decryption will
23 // cause a random plaintext of this length to be returned rather than
24 // an error. These alternatives happen in constant time.
28 // EncryptPKCS1v15 encrypts the given message with RSA and the padding
29 // scheme from PKCS#1 v1.5. The message must be no longer than the
30 // length of the public modulus minus 11 bytes.
32 // The rand parameter is used as a source of entropy to ensure that
33 // encrypting the same message twice doesn't result in the same
36 // WARNING: use of this function to encrypt plaintexts other than
37 // session keys is dangerous. Use RSA OAEP in new protocols.
38 func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error) {
39 if err := checkPub(pub); err != nil {
44 return nil, ErrMessageTooLong
47 if boring.Enabled && random == boring.RandReader {
48 bkey, err := boringPublicKey(pub)
52 return boring.EncryptRSAPKCS1(bkey, msg)
54 boring.UnreachableExceptTests()
56 // EM = 0x00 || 0x02 || PS || 0x00 || M
59 ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):]
60 err := nonZeroRandomBytes(ps, random)
64 em[len(em)-len(msg)-1] = 0
68 var bkey *boring.PublicKeyRSA
69 bkey, err = boringPublicKey(pub)
73 return boring.EncryptRSANoPadding(bkey, em)
76 m := new(big.Int).SetBytes(em)
77 c := encrypt(new(big.Int), pub, m)
78 copyWithLeftPad(em, c.Bytes())
82 // DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5.
83 // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
85 // Note that whether this function returns an error or not discloses secret
86 // information. If an attacker can cause this function to run repeatedly and
87 // learn whether each instance returned an error then they can decrypt and
88 // forge signatures as if they had the private key. See
89 // DecryptPKCS1v15SessionKey for a way of solving this problem.
90 func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error) {
91 if err := checkPub(&priv.PublicKey); err != nil {
96 boringFakeRandomBlind(rand, priv)
97 bkey, err := boringPrivateKey(priv)
101 out, err := boring.DecryptRSAPKCS1(bkey, ciphertext)
103 return nil, ErrDecryption
108 valid, out, index, err := decryptPKCS1v15(rand, priv, ciphertext)
113 return nil, ErrDecryption
115 return out[index:], nil
118 // DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5.
119 // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
120 // It returns an error if the ciphertext is the wrong length or if the
121 // ciphertext is greater than the public modulus. Otherwise, no error is
122 // returned. If the padding is valid, the resulting plaintext message is copied
123 // into key. Otherwise, key is unchanged. These alternatives occur in constant
124 // time. It is intended that the user of this function generate a random
125 // session key beforehand and continue the protocol with the resulting value.
126 // This will remove any possibility that an attacker can learn any information
127 // about the plaintext.
128 // See ``Chosen Ciphertext Attacks Against Protocols Based on the RSA
129 // Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology
132 // Note that if the session key is too small then it may be possible for an
133 // attacker to brute-force it. If they can do that then they can learn whether
134 // a random value was used (because it'll be different for the same ciphertext)
135 // and thus whether the padding was correct. This defeats the point of this
136 // function. Using at least a 16-byte key will protect against this attack.
137 func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error {
138 if err := checkPub(&priv.PublicKey); err != nil {
142 if k-(len(key)+3+8) < 0 {
146 valid, em, index, err := decryptPKCS1v15(rand, priv, ciphertext)
152 // This should be impossible because decryptPKCS1v15 always
153 // returns the full slice.
157 valid &= subtle.ConstantTimeEq(int32(len(em)-index), int32(len(key)))
158 subtle.ConstantTimeCopy(valid, key, em[len(em)-len(key):])
162 // decryptPKCS1v15 decrypts ciphertext using priv and blinds the operation if
163 // rand is not nil. It returns one or zero in valid that indicates whether the
164 // plaintext was correctly structured. In either case, the plaintext is
165 // returned in em so that it may be read independently of whether it was valid
166 // in order to maintain constant memory access patterns. If the plaintext was
167 // valid then index contains the index of the original message in em.
168 func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error) {
176 boringFakeRandomBlind(rand, priv)
177 var bkey *boring.PrivateKeyRSA
178 bkey, err = boringPrivateKey(priv)
182 em, err = boring.DecryptRSANoPadding(bkey, ciphertext)
187 c := new(big.Int).SetBytes(ciphertext)
189 m, err = decrypt(rand, priv, c)
193 em = leftPad(m.Bytes(), k)
196 firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
197 secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2)
199 // The remainder of the plaintext must be a string of non-zero random
200 // octets, followed by a 0, followed by the message.
201 // lookingForIndex: 1 iff we are still looking for the zero.
202 // index: the offset of the first zero byte.
205 for i := 2; i < len(em); i++ {
206 equals0 := subtle.ConstantTimeByteEq(em[i], 0)
207 index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index)
208 lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex)
211 // The PS padding must be at least 8 bytes long, and it starts two
213 validPS := subtle.ConstantTimeLessOrEq(2+8, index)
215 valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1) & validPS
216 index = subtle.ConstantTimeSelect(valid, index+1, 0)
217 return valid, em, index, nil
220 // nonZeroRandomBytes fills the given slice with non-zero random octets.
221 func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
222 _, err = io.ReadFull(rand, s)
227 for i := 0; i < len(s); i++ {
229 _, err = io.ReadFull(rand, s[i:i+1])
233 // In tests, the PRNG may return all zeros so we do
234 // this to break the loop.
242 // These are ASN1 DER structures:
243 // DigestInfo ::= SEQUENCE {
244 // digestAlgorithm AlgorithmIdentifier,
245 // digest OCTET STRING
247 // For performance, we don't use the generic ASN1 encoder. Rather, we
248 // precompute a prefix of the digest value that makes a valid ASN1 DER string
249 // with the correct contents.
250 var hashPrefixes = map[crypto.Hash][]byte{
251 crypto.MD5: {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
252 crypto.SHA1: {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14},
253 crypto.SHA224: {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
254 crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
255 crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
256 crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
257 crypto.MD5SHA1: {}, // A special TLS case which doesn't use an ASN1 prefix.
258 crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14},
261 // SignPKCS1v15 calculates the signature of hashed using
262 // RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. Note that hashed must
263 // be the result of hashing the input message using the given hash
264 // function. If hash is zero, hashed is signed directly. This isn't
265 // advisable except for interoperability.
267 // If rand is not nil then RSA blinding will be used to avoid timing
268 // side-channel attacks.
270 // This function is deterministic. Thus, if the set of possible
271 // messages is small, an attacker may be able to build a map from
272 // messages to signatures and identify the signed messages. As ever,
273 // signatures provide authenticity, not confidentiality.
274 func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
275 hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
280 tLen := len(prefix) + hashLen
283 return nil, ErrMessageTooLong
287 boringFakeRandomBlind(random, priv)
288 bkey, err := boringPrivateKey(priv)
292 return boring.SignRSAPKCS1v15(bkey, hash, hashed)
295 // EM = 0x00 || 0x01 || PS || 0x00 || T
296 em := make([]byte, k)
298 for i := 2; i < k-tLen-1; i++ {
301 copy(em[k-tLen:k-hashLen], prefix)
302 copy(em[k-hashLen:k], hashed)
304 m := new(big.Int).SetBytes(em)
305 c, err := decryptAndCheck(random, priv, m)
310 copyWithLeftPad(em, c.Bytes())
314 // VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature.
315 // hashed is the result of hashing the input message using the given hash
316 // function and sig is the signature. A valid signature is indicated by
317 // returning a nil error. If hash is zero then hashed is used directly. This
318 // isn't advisable except for interoperability.
319 func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
321 bkey, err := boringPublicKey(pub)
325 if err := boring.VerifyRSAPKCS1v15(bkey, hash, hashed, sig); err != nil {
326 return ErrVerification
331 hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
336 tLen := len(prefix) + hashLen
339 return ErrVerification
342 c := new(big.Int).SetBytes(sig)
343 m := encrypt(new(big.Int), pub, c)
344 em := leftPad(m.Bytes(), k)
345 // EM = 0x00 || 0x01 || PS || 0x00 || T
347 ok := subtle.ConstantTimeByteEq(em[0], 0)
348 ok &= subtle.ConstantTimeByteEq(em[1], 1)
349 ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed)
350 ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix)
351 ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0)
353 for i := 2; i < k-tLen-1; i++ {
354 ok &= subtle.ConstantTimeByteEq(em[i], 0xff)
358 return ErrVerification
364 func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) {
365 // Special case: crypto.Hash(0) is used to indicate that the data is
368 return inLen, nil, nil
371 hashLen = hash.Size()
372 if inLen != hashLen {
373 return 0, nil, errors.New("crypto/rsa: input must be hashed message")
375 prefix, ok := hashPrefixes[hash]
377 return 0, nil, errors.New("crypto/rsa: unsupported hash function")
382 // copyWithLeftPad copies src to the end of dest, padding with zero bytes as
384 func copyWithLeftPad(dest, src []byte) {
385 numPaddingBytes := len(dest) - len(src)
386 for i := 0; i < numPaddingBytes; i++ {
389 copy(dest[numPaddingBytes:], src)