github.com/dorkamotorka/go/src@v0.0.0-20230614113921-187095f0e316/crypto/rsa/pkcs1v15.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 6 7 import ( 8 "crypto" 9 "crypto/internal/boring" 10 "crypto/internal/randutil" 11 "crypto/subtle" 12 "errors" 13 "io" 14 ) 15 16 // This file implements encryption and decryption using PKCS #1 v1.5 padding. 17 18 // PKCS1v15DecryptOptions 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. 25 SessionKeyLen int 26 } 27 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. 31 // 32 // The random parameter is used as a source of entropy to ensure that 33 // encrypting the same message twice doesn't result in the same 34 // ciphertext. 35 // 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 randutil.MaybeReadByte(random) 40 41 if err := checkPub(pub); err != nil { 42 return nil, err 43 } 44 k := pub.Size() 45 if len(msg) > k-11 { 46 return nil, ErrMessageTooLong 47 } 48 49 if boring.Enabled && random == boring.RandReader { 50 bkey, err := boringPublicKey(pub) 51 if err != nil { 52 return nil, err 53 } 54 return boring.EncryptRSAPKCS1(bkey, msg) 55 } 56 boring.UnreachableExceptTests() 57 58 // EM = 0x00 || 0x02 || PS || 0x00 || M 59 em := make([]byte, k) 60 em[1] = 2 61 ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):] 62 err := nonZeroRandomBytes(ps, random) 63 if err != nil { 64 return nil, err 65 } 66 em[len(em)-len(msg)-1] = 0 67 copy(mm, msg) 68 69 if boring.Enabled { 70 var bkey *boring.PublicKeyRSA 71 bkey, err = boringPublicKey(pub) 72 if err != nil { 73 return nil, err 74 } 75 return boring.EncryptRSANoPadding(bkey, em) 76 } 77 78 return encrypt(pub, em) 79 } 80 81 // DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5. 82 // The random parameter is legacy and ignored, and it can be as nil. 83 // 84 // Note that whether this function returns an error or not discloses secret 85 // information. If an attacker can cause this function to run repeatedly and 86 // learn whether each instance returned an error then they can decrypt and 87 // forge signatures as if they had the private key. See 88 // DecryptPKCS1v15SessionKey for a way of solving this problem. 89 func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error) { 90 if err := checkPub(&priv.PublicKey); err != nil { 91 return nil, err 92 } 93 94 if boring.Enabled { 95 bkey, err := boringPrivateKey(priv) 96 if err != nil { 97 return nil, err 98 } 99 out, err := boring.DecryptRSAPKCS1(bkey, ciphertext) 100 if err != nil { 101 return nil, ErrDecryption 102 } 103 return out, nil 104 } 105 106 valid, out, index, err := decryptPKCS1v15(priv, ciphertext) 107 if err != nil { 108 return nil, err 109 } 110 if valid == 0 { 111 return nil, ErrDecryption 112 } 113 return out[index:], nil 114 } 115 116 // DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding 117 // scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it 118 // can be nil. 119 // 120 // DecryptPKCS1v15SessionKey returns an error if the ciphertext is the wrong 121 // length or if the ciphertext is greater than the public modulus. Otherwise, no 122 // error is returned. If the padding is valid, the resulting plaintext message 123 // is copied into key. Otherwise, key is unchanged. These alternatives occur in 124 // constant time. It is intended that the user of this function generate a 125 // random session key beforehand and continue the protocol with the resulting 126 // value. 127 // 128 // Note that if the session key is too small then it may be possible for an 129 // attacker to brute-force it. If they can do that then they can learn whether a 130 // random value was used (because it'll be different for the same ciphertext) 131 // and thus whether the padding was correct. This also defeats the point of this 132 // function. Using at least a 16-byte key will protect against this attack. 133 // 134 // This method implements protections against Bleichenbacher chosen ciphertext 135 // attacks [0] described in RFC 3218 Section 2.3.2 [1]. While these protections 136 // make a Bleichenbacher attack significantly more difficult, the protections 137 // are only effective if the rest of the protocol which uses 138 // DecryptPKCS1v15SessionKey is designed with these considerations in mind. In 139 // particular, if any subsequent operations which use the decrypted session key 140 // leak any information about the key (e.g. whether it is a static or random 141 // key) then the mitigations are defeated. This method must be used extremely 142 // carefully, and typically should only be used when absolutely necessary for 143 // compatibility with an existing protocol (such as TLS) that is designed with 144 // these properties in mind. 145 // 146 // - [0] “Chosen Ciphertext Attacks Against Protocols Based on the RSA Encryption 147 // Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology (Crypto '98) 148 // - [1] RFC 3218, Preventing the Million Message Attack on CMS, 149 // https://www.rfc-editor.org/rfc/rfc3218.html 150 func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error { 151 if err := checkPub(&priv.PublicKey); err != nil { 152 return err 153 } 154 k := priv.Size() 155 if k-(len(key)+3+8) < 0 { 156 return ErrDecryption 157 } 158 159 valid, em, index, err := decryptPKCS1v15(priv, ciphertext) 160 if err != nil { 161 return err 162 } 163 164 if len(em) != k { 165 // This should be impossible because decryptPKCS1v15 always 166 // returns the full slice. 167 return ErrDecryption 168 } 169 170 valid &= subtle.ConstantTimeEq(int32(len(em)-index), int32(len(key))) 171 subtle.ConstantTimeCopy(valid, key, em[len(em)-len(key):]) 172 return nil 173 } 174 175 // decryptPKCS1v15 decrypts ciphertext using priv. It returns one or zero in 176 // valid that indicates whether the plaintext was correctly structured. 177 // In either case, the plaintext is returned in em so that it may be read 178 // independently of whether it was valid in order to maintain constant memory 179 // access patterns. If the plaintext was valid then index contains the index of 180 // the original message in em, to allow constant time padding removal. 181 func decryptPKCS1v15(priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error) { 182 k := priv.Size() 183 if k < 11 { 184 err = ErrDecryption 185 return 186 } 187 188 if boring.Enabled { 189 var bkey *boring.PrivateKeyRSA 190 bkey, err = boringPrivateKey(priv) 191 if err != nil { 192 return 193 } 194 em, err = boring.DecryptRSANoPadding(bkey, ciphertext) 195 if err != nil { 196 return 197 } 198 } else { 199 em, err = decrypt(priv, ciphertext, noCheck) 200 if err != nil { 201 return 202 } 203 } 204 205 firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0) 206 secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2) 207 208 // The remainder of the plaintext must be a string of non-zero random 209 // octets, followed by a 0, followed by the message. 210 // lookingForIndex: 1 iff we are still looking for the zero. 211 // index: the offset of the first zero byte. 212 lookingForIndex := 1 213 214 for i := 2; i < len(em); i++ { 215 equals0 := subtle.ConstantTimeByteEq(em[i], 0) 216 index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index) 217 lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex) 218 } 219 220 // The PS padding must be at least 8 bytes long, and it starts two 221 // bytes into em. 222 validPS := subtle.ConstantTimeLessOrEq(2+8, index) 223 224 valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1) & validPS 225 index = subtle.ConstantTimeSelect(valid, index+1, 0) 226 return valid, em, index, nil 227 } 228 229 // nonZeroRandomBytes fills the given slice with non-zero random octets. 230 func nonZeroRandomBytes(s []byte, random io.Reader) (err error) { 231 _, err = io.ReadFull(random, s) 232 if err != nil { 233 return 234 } 235 236 for i := 0; i < len(s); i++ { 237 for s[i] == 0 { 238 _, err = io.ReadFull(random, s[i:i+1]) 239 if err != nil { 240 return 241 } 242 // In tests, the PRNG may return all zeros so we do 243 // this to break the loop. 244 s[i] ^= 0x42 245 } 246 } 247 248 return 249 } 250 251 // These are ASN1 DER structures: 252 // 253 // DigestInfo ::= SEQUENCE { 254 // digestAlgorithm AlgorithmIdentifier, 255 // digest OCTET STRING 256 // } 257 // 258 // For performance, we don't use the generic ASN1 encoder. Rather, we 259 // precompute a prefix of the digest value that makes a valid ASN1 DER string 260 // with the correct contents. 261 var hashPrefixes = map[crypto.Hash][]byte{ 262 crypto.MD5: {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10}, 263 crypto.SHA1: {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14}, 264 crypto.SHA224: {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c}, 265 crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20}, 266 crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30}, 267 crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40}, 268 crypto.MD5SHA1: {}, // A special TLS case which doesn't use an ASN1 prefix. 269 crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14}, 270 } 271 272 // SignPKCS1v15 calculates the signature of hashed using 273 // RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5. Note that hashed must 274 // be the result of hashing the input message using the given hash 275 // function. If hash is zero, hashed is signed directly. This isn't 276 // advisable except for interoperability. 277 // 278 // The random parameter is legacy and ignored, and it can be as nil. 279 // 280 // This function is deterministic. Thus, if the set of possible 281 // messages is small, an attacker may be able to build a map from 282 // messages to signatures and identify the signed messages. As ever, 283 // signatures provide authenticity, not confidentiality. 284 func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) { 285 hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed)) 286 if err != nil { 287 return nil, err 288 } 289 290 tLen := len(prefix) + hashLen 291 k := priv.Size() 292 if k < tLen+11 { 293 return nil, ErrMessageTooLong 294 } 295 296 if boring.Enabled { 297 bkey, err := boringPrivateKey(priv) 298 if err != nil { 299 return nil, err 300 } 301 return boring.SignRSAPKCS1v15(bkey, hash, hashed) 302 } 303 304 // EM = 0x00 || 0x01 || PS || 0x00 || T 305 em := make([]byte, k) 306 em[1] = 1 307 for i := 2; i < k-tLen-1; i++ { 308 em[i] = 0xff 309 } 310 copy(em[k-tLen:k-hashLen], prefix) 311 copy(em[k-hashLen:k], hashed) 312 313 return decrypt(priv, em, withCheck) 314 } 315 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 { 322 if boring.Enabled { 323 bkey, err := boringPublicKey(pub) 324 if err != nil { 325 return err 326 } 327 if err := boring.VerifyRSAPKCS1v15(bkey, hash, hashed, sig); err != nil { 328 return ErrVerification 329 } 330 return nil 331 } 332 333 hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed)) 334 if err != nil { 335 return err 336 } 337 338 tLen := len(prefix) + hashLen 339 k := pub.Size() 340 if k < tLen+11 { 341 return ErrVerification 342 } 343 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. 347 if k != len(sig) { 348 return ErrVerification 349 } 350 351 em, err := encrypt(pub, sig) 352 if err != nil { 353 return ErrVerification 354 } 355 // EM = 0x00 || 0x01 || PS || 0x00 || T 356 357 ok := subtle.ConstantTimeByteEq(em[0], 0) 358 ok &= subtle.ConstantTimeByteEq(em[1], 1) 359 ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed) 360 ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix) 361 ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0) 362 363 for i := 2; i < k-tLen-1; i++ { 364 ok &= subtle.ConstantTimeByteEq(em[i], 0xff) 365 } 366 367 if ok != 1 { 368 return ErrVerification 369 } 370 371 return nil 372 } 373 374 func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) { 375 // Special case: crypto.Hash(0) is used to indicate that the data is 376 // signed directly. 377 if hash == 0 { 378 return inLen, nil, nil 379 } 380 381 hashLen = hash.Size() 382 if inLen != hashLen { 383 return 0, nil, errors.New("crypto/rsa: input must be hashed message") 384 } 385 prefix, ok := hashPrefixes[hash] 386 if !ok { 387 return 0, nil, errors.New("crypto/rsa: unsupported hash function") 388 } 389 return 390 }