pkcs1v15.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. //
  175. // DigestInfo ::= SEQUENCE {
  176. // digestAlgorithm AlgorithmIdentifier,
  177. // digest OCTET STRING
  178. // }
  179. //
  180. // For performance, we don't use the generic ASN1 encoder. Rather, we
  181. // precompute a prefix of the digest value that makes a valid ASN1 DER string
  182. // with the correct contents.
  183. var hashPrefixes = map[crypto.Hash][]byte{
  184. crypto.MD5: {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
  185. crypto.SHA1: {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14},
  186. crypto.SHA224: {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
  187. crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
  188. crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
  189. crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
  190. crypto.MD5SHA1: {}, // A special TLS case which doesn't use an ASN1 prefix.
  191. crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14},
  192. }
  193. // SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5.
  194. // Note that hashed must be the result of hashing the input message using the
  195. // given hash function. If hash is zero, hashed is signed directly. This isn't
  196. // advisable except for interoperability.
  197. //
  198. // If rand is not nil then RSA blinding will be used to avoid timing side-channel attacks.
  199. //
  200. // This function is deterministic. Thus, if the set of possible messages is
  201. // small, an attacker may be able to build a map from messages to signatures
  202. // and identify the signed messages. As ever, signatures provide authenticity,
  203. // not confidentiality.
  204. func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err error) {
  205. hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
  206. if err != nil {
  207. return
  208. }
  209. tLen := len(prefix) + hashLen
  210. k := (priv.N.BitLen() + 7) / 8
  211. if k < tLen+11 {
  212. return nil, ErrMessageTooLong
  213. }
  214. // EM = 0x00 || 0x01 || PS || 0x00 || T
  215. em := make([]byte, k)
  216. em[1] = 1
  217. for i := 2; i < k-tLen-1; i++ {
  218. em[i] = 0xff
  219. }
  220. copy(em[k-tLen:k-hashLen], prefix)
  221. copy(em[k-hashLen:k], hashed)
  222. m := new(big.Int).SetBytes(em)
  223. c, err := decryptAndCheck(rand, priv, m)
  224. if err != nil {
  225. return
  226. }
  227. copyWithLeftPad(em, c.Bytes())
  228. s = em
  229. return
  230. }
  231. // VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature.
  232. // hashed is the result of hashing the input message using the given hash
  233. // function and sig is the signature. A valid signature is indicated by
  234. // returning a nil error. If hash is zero then hashed is used directly. This
  235. // isn't advisable except for interoperability.
  236. func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err error) {
  237. hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
  238. if err != nil {
  239. return
  240. }
  241. tLen := len(prefix) + hashLen
  242. k := (pub.N.BitLen() + 7) / 8
  243. if k < tLen+11 {
  244. err = ErrVerification
  245. return
  246. }
  247. c := new(big.Int).SetBytes(sig)
  248. m := encrypt(new(big.Int), pub, c)
  249. em := leftPad(m.Bytes(), k)
  250. // EM = 0x00 || 0x01 || PS || 0x00 || T
  251. ok := subtle.ConstantTimeByteEq(em[0], 0)
  252. ok &= subtle.ConstantTimeByteEq(em[1], 1)
  253. ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed)
  254. ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix)
  255. ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0)
  256. for i := 2; i < k-tLen-1; i++ {
  257. ok &= subtle.ConstantTimeByteEq(em[i], 0xff)
  258. }
  259. if ok != 1 {
  260. return ErrVerification
  261. }
  262. return nil
  263. }
  264. func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) {
  265. // Special case: crypto.Hash(0) is used to indicate that the data is
  266. // signed directly.
  267. if hash == 0 {
  268. return inLen, nil, nil
  269. }
  270. hashLen = hash.Size()
  271. if inLen != hashLen {
  272. return 0, nil, errors.New("crypto/rsa: input must be hashed message")
  273. }
  274. prefix, ok := hashPrefixes[hash]
  275. if !ok {
  276. return 0, nil, errors.New("crypto/rsa: unsupported hash function")
  277. }
  278. return
  279. }
  280. // copyWithLeftPad copies src to the end of dest, padding with zero bytes as
  281. // needed.
  282. func copyWithLeftPad(dest, src []byte) {
  283. numPaddingBytes := len(dest) - len(src)
  284. for i := 0; i < numPaddingBytes; i++ {
  285. dest[i] = 0
  286. }
  287. copy(dest[numPaddingBytes:], src)
  288. }