本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

326 lines
11KB

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