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