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