Source file src/crypto/rsa/pkcs1v15.go

     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/subtle"
    10  	"errors"
    11  	"io"
    12  	"math/big"
    13  
    14  	"crypto/internal/randutil"
    15  )
    16  
    17  // This file implements encryption and decryption using PKCS #1 v1.5 padding.
    18  
    19  // PKCS1v15DecrypterOpts is for passing options to PKCS #1 v1.5 decryption using
    20  // the crypto.Decrypter interface.
    21  type PKCS1v15DecryptOptions struct {
    22  	// SessionKeyLen is the length of the session key that is being
    23  	// decrypted. If not zero, then a padding error during decryption will
    24  	// cause a random plaintext of this length to be returned rather than
    25  	// an error. These alternatives happen in constant time.
    26  	SessionKeyLen int
    27  }
    28  
    29  // EncryptPKCS1v15 encrypts the given message with RSA and the padding
    30  // scheme from PKCS #1 v1.5.  The message must be no longer than the
    31  // length of the public modulus minus 11 bytes.
    32  //
    33  // The rand parameter is used as a source of entropy to ensure that
    34  // encrypting the same message twice doesn't result in the same
    35  // ciphertext.
    36  //
    37  // WARNING: use of this function to encrypt plaintexts other than
    38  // session keys is dangerous. Use RSA OAEP in new protocols.
    39  func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) ([]byte, error) {
    40  	randutil.MaybeReadByte(rand)
    41  
    42  	if err := checkPub(pub); err != nil {
    43  		return nil, err
    44  	}
    45  	k := pub.Size()
    46  	if len(msg) > k-11 {
    47  		return nil, ErrMessageTooLong
    48  	}
    49  
    50  	// EM = 0x00 || 0x02 || PS || 0x00 || M
    51  	em := make([]byte, k)
    52  	em[1] = 2
    53  	ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):]
    54  	err := nonZeroRandomBytes(ps, rand)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	em[len(em)-len(msg)-1] = 0
    59  	copy(mm, msg)
    60  
    61  	m := new(big.Int).SetBytes(em)
    62  	c := encrypt(new(big.Int), pub, m)
    63  
    64  	return c.FillBytes(em), nil
    65  }
    66  
    67  // DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5.
    68  // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
    69  //
    70  // Note that whether this function returns an error or not discloses secret
    71  // information. If an attacker can cause this function to run repeatedly and
    72  // learn whether each instance returned an error then they can decrypt and
    73  // forge signatures as if they had the private key. See
    74  // DecryptPKCS1v15SessionKey for a way of solving this problem.
    75  func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error) {
    76  	if err := checkPub(&priv.PublicKey); err != nil {
    77  		return nil, err
    78  	}
    79  	valid, out, index, err := decryptPKCS1v15(rand, priv, ciphertext)
    80  	if err != nil {
    81  		return nil, err
    82  	}
    83  	if valid == 0 {
    84  		return nil, ErrDecryption
    85  	}
    86  	return out[index:], nil
    87  }
    88  
    89  // DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS #1 v1.5.
    90  // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
    91  // It returns an error if the ciphertext is the wrong length or if the
    92  // ciphertext is greater than the public modulus. Otherwise, no error is
    93  // returned. If the padding is valid, the resulting plaintext message is copied
    94  // into key. Otherwise, key is unchanged. These alternatives occur in constant
    95  // time. It is intended that the user of this function generate a random
    96  // session key beforehand and continue the protocol with the resulting value.
    97  // This will remove any possibility that an attacker can learn any information
    98  // about the plaintext.
    99  // See ``Chosen Ciphertext Attacks Against Protocols Based on the RSA
   100  // Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology
   101  // (Crypto '98).
   102  //
   103  // Note that if the session key is too small then it may be possible for an
   104  // attacker to brute-force it. If they can do that then they can learn whether
   105  // a random value was used (because it'll be different for the same ciphertext)
   106  // and thus whether the padding was correct. This defeats the point of this
   107  // function. Using at least a 16-byte key will protect against this attack.
   108  func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error {
   109  	if err := checkPub(&priv.PublicKey); err != nil {
   110  		return err
   111  	}
   112  	k := priv.Size()
   113  	if k-(len(key)+3+8) < 0 {
   114  		return ErrDecryption
   115  	}
   116  
   117  	valid, em, index, err := decryptPKCS1v15(rand, priv, ciphertext)
   118  	if err != nil {
   119  		return err
   120  	}
   121  
   122  	if len(em) != k {
   123  		// This should be impossible because decryptPKCS1v15 always
   124  		// returns the full slice.
   125  		return ErrDecryption
   126  	}
   127  
   128  	valid &= subtle.ConstantTimeEq(int32(len(em)-index), int32(len(key)))
   129  	subtle.ConstantTimeCopy(valid, key, em[len(em)-len(key):])
   130  	return nil
   131  }
   132  
   133  // decryptPKCS1v15 decrypts ciphertext using priv and blinds the operation if
   134  // rand is not nil. It returns one or zero in valid that indicates whether the
   135  // plaintext was correctly structured. In either case, the plaintext is
   136  // returned in em so that it may be read independently of whether it was valid
   137  // in order to maintain constant memory access patterns. If the plaintext was
   138  // valid then index contains the index of the original message in em.
   139  func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error) {
   140  	k := priv.Size()
   141  	if k < 11 {
   142  		err = ErrDecryption
   143  		return
   144  	}
   145  
   146  	c := new(big.Int).SetBytes(ciphertext)
   147  	m, err := decrypt(rand, priv, c)
   148  	if err != nil {
   149  		return
   150  	}
   151  
   152  	em = m.FillBytes(make([]byte, k))
   153  	firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
   154  	secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2)
   155  
   156  	// The remainder of the plaintext must be a string of non-zero random
   157  	// octets, followed by a 0, followed by the message.
   158  	//   lookingForIndex: 1 iff we are still looking for the zero.
   159  	//   index: the offset of the first zero byte.
   160  	lookingForIndex := 1
   161  
   162  	for i := 2; i < len(em); i++ {
   163  		equals0 := subtle.ConstantTimeByteEq(em[i], 0)
   164  		index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index)
   165  		lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex)
   166  	}
   167  
   168  	// The PS padding must be at least 8 bytes long, and it starts two
   169  	// bytes into em.
   170  	validPS := subtle.ConstantTimeLessOrEq(2+8, index)
   171  
   172  	valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1) & validPS
   173  	index = subtle.ConstantTimeSelect(valid, index+1, 0)
   174  	return valid, em, index, nil
   175  }
   176  
   177  // nonZeroRandomBytes fills the given slice with non-zero random octets.
   178  func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
   179  	_, err = io.ReadFull(rand, s)
   180  	if err != nil {
   181  		return
   182  	}
   183  
   184  	for i := 0; i < len(s); i++ {
   185  		for s[i] == 0 {
   186  			_, err = io.ReadFull(rand, s[i:i+1])
   187  			if err != nil {
   188  				return
   189  			}
   190  			// In tests, the PRNG may return all zeros so we do
   191  			// this to break the loop.
   192  			s[i] ^= 0x42
   193  		}
   194  	}
   195  
   196  	return
   197  }
   198  
   199  // These are ASN1 DER structures:
   200  //   DigestInfo ::= SEQUENCE {
   201  //     digestAlgorithm AlgorithmIdentifier,
   202  //     digest OCTET STRING
   203  //   }
   204  // For performance, we don't use the generic ASN1 encoder. Rather, we
   205  // precompute a prefix of the digest value that makes a valid ASN1 DER string
   206  // with the correct contents.
   207  var hashPrefixes = map[crypto.Hash][]byte{
   208  	crypto.MD5:       {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
   209  	crypto.SHA1:      {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14},
   210  	crypto.SHA224:    {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
   211  	crypto.SHA256:    {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
   212  	crypto.SHA384:    {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
   213  	crypto.SHA512:    {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
   214  	crypto.MD5SHA1:   {}, // A special TLS case which doesn't use an ASN1 prefix.
   215  	crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14},
   216  }
   217  
   218  // SignPKCS1v15 calculates the signature of hashed using
   219  // RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5.  Note that hashed must
   220  // be the result of hashing the input message using the given hash
   221  // function. If hash is zero, hashed is signed directly. This isn't
   222  // advisable except for interoperability.
   223  //
   224  // If rand is not nil then RSA blinding will be used to avoid timing
   225  // side-channel attacks.
   226  //
   227  // This function is deterministic. Thus, if the set of possible
   228  // messages is small, an attacker may be able to build a map from
   229  // messages to signatures and identify the signed messages. As ever,
   230  // signatures provide authenticity, not confidentiality.
   231  func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
   232  	hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
   233  	if err != nil {
   234  		return nil, err
   235  	}
   236  
   237  	tLen := len(prefix) + hashLen
   238  	k := priv.Size()
   239  	if k < tLen+11 {
   240  		return nil, ErrMessageTooLong
   241  	}
   242  
   243  	// EM = 0x00 || 0x01 || PS || 0x00 || T
   244  	em := make([]byte, k)
   245  	em[1] = 1
   246  	for i := 2; i < k-tLen-1; i++ {
   247  		em[i] = 0xff
   248  	}
   249  	copy(em[k-tLen:k-hashLen], prefix)
   250  	copy(em[k-hashLen:k], hashed)
   251  
   252  	m := new(big.Int).SetBytes(em)
   253  	c, err := decryptAndCheck(rand, priv, m)
   254  	if err != nil {
   255  		return nil, err
   256  	}
   257  
   258  	return c.FillBytes(em), nil
   259  }
   260  
   261  // VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature.
   262  // hashed is the result of hashing the input message using the given hash
   263  // function and sig is the signature. A valid signature is indicated by
   264  // returning a nil error. If hash is zero then hashed is used directly. This
   265  // isn't advisable except for interoperability.
   266  func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
   267  	hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
   268  	if err != nil {
   269  		return err
   270  	}
   271  
   272  	tLen := len(prefix) + hashLen
   273  	k := pub.Size()
   274  	if k < tLen+11 {
   275  		return ErrVerification
   276  	}
   277  
   278  	// RFC 8017 Section 8.2.2: If the length of the signature S is not k
   279  	// octets (where k is the length in octets of the RSA modulus n), output
   280  	// "invalid signature" and stop.
   281  	if k != len(sig) {
   282  		return ErrVerification
   283  	}
   284  
   285  	c := new(big.Int).SetBytes(sig)
   286  	m := encrypt(new(big.Int), pub, c)
   287  	em := m.FillBytes(make([]byte, k))
   288  	// EM = 0x00 || 0x01 || PS || 0x00 || T
   289  
   290  	ok := subtle.ConstantTimeByteEq(em[0], 0)
   291  	ok &= subtle.ConstantTimeByteEq(em[1], 1)
   292  	ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed)
   293  	ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix)
   294  	ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0)
   295  
   296  	for i := 2; i < k-tLen-1; i++ {
   297  		ok &= subtle.ConstantTimeByteEq(em[i], 0xff)
   298  	}
   299  
   300  	if ok != 1 {
   301  		return ErrVerification
   302  	}
   303  
   304  	return nil
   305  }
   306  
   307  func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) {
   308  	// Special case: crypto.Hash(0) is used to indicate that the data is
   309  	// signed directly.
   310  	if hash == 0 {
   311  		return inLen, nil, nil
   312  	}
   313  
   314  	hashLen = hash.Size()
   315  	if inLen != hashLen {
   316  		return 0, nil, errors.New("crypto/rsa: input must be hashed message")
   317  	}
   318  	prefix, ok := hashPrefixes[hash]
   319  	if !ok {
   320  		return 0, nil, errors.New("crypto/rsa: unsupported hash function")
   321  	}
   322  	return
   323  }
   324  

View as plain text