PKCS1_OAEP.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/PKCS1_OAEP.py : PKCS#1 OAEP
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. from Crypto.Signature.pss import MGF1
  23. import Crypto.Hash.SHA1
  24. from Crypto.Util.py3compat import _copy_bytes
  25. import Crypto.Util.number
  26. from Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes
  27. from Crypto.Util.strxor import strxor
  28. from Crypto import Random
  29. from ._pkcs1_oaep_decode import oaep_decode
  30. class PKCS1OAEP_Cipher:
  31. """Cipher object for PKCS#1 OAEP.
  32. Do not create directly: use :func:`new` instead."""
  33. def __init__(self, key, hashAlgo, mgfunc, label, randfunc):
  34. """Initialize this PKCS#1 OAEP cipher object.
  35. :Parameters:
  36. key : an RSA key object
  37. If a private half is given, both encryption and decryption are possible.
  38. If a public half is given, only encryption is possible.
  39. hashAlgo : hash object
  40. The hash function to use. This can be a module under `Crypto.Hash`
  41. or an existing hash object created from any of such modules. If not specified,
  42. `Crypto.Hash.SHA1` is used, matching the RSAES-OAEP default
  43. defined in RFC8017. New protocols should use SHA-256 or a stronger
  44. hash function.
  45. mgfunc : callable
  46. A mask generation function that accepts two parameters: a string to
  47. use as seed, and the lenth of the mask to generate, in bytes.
  48. If not specified, the standard MGF1 consistent with ``hashAlgo`` is used (a safe choice).
  49. label : bytes/bytearray/memoryview
  50. A label to apply to this particular encryption. If not specified,
  51. an empty string is used. Specifying a label does not improve
  52. security.
  53. randfunc : callable
  54. A function that returns random bytes.
  55. :attention: Modify the mask generation function only if you know what you are doing.
  56. Sender and receiver must use the same one.
  57. """
  58. self._key = key
  59. if hashAlgo:
  60. self._hashObj = hashAlgo
  61. else:
  62. self._hashObj = Crypto.Hash.SHA1
  63. if mgfunc:
  64. self._mgf = mgfunc
  65. else:
  66. self._mgf = lambda x, y: MGF1(x, y, self._hashObj)
  67. self._label = _copy_bytes(None, None, label)
  68. self._randfunc = randfunc
  69. def can_encrypt(self):
  70. """Legacy function to check if you can call :meth:`encrypt`.
  71. .. deprecated:: 3.0"""
  72. return self._key.can_encrypt()
  73. def can_decrypt(self):
  74. """Legacy function to check if you can call :meth:`decrypt`.
  75. .. deprecated:: 3.0"""
  76. return self._key.can_decrypt()
  77. def encrypt(self, message):
  78. """Encrypt a message with PKCS#1 OAEP.
  79. :param message:
  80. The message to encrypt, also known as plaintext. It can be of
  81. variable length, but not longer than the RSA modulus (in bytes)
  82. minus 2, minus twice the hash output size.
  83. For instance, if you use RSA 2048 and SHA-256, the longest message
  84. you can encrypt is 190 byte long.
  85. :type message: bytes/bytearray/memoryview
  86. :returns: The ciphertext, as large as the RSA modulus.
  87. :rtype: bytes
  88. :raises ValueError:
  89. if the message is too long.
  90. """
  91. # See 7.1.1 in RFC3447
  92. modBits = Crypto.Util.number.size(self._key.n)
  93. k = ceil_div(modBits, 8) # Convert from bits to bytes
  94. hLen = self._hashObj.digest_size
  95. mLen = len(message)
  96. # Step 1b
  97. ps_len = k - mLen - 2 * hLen - 2
  98. if ps_len < 0:
  99. raise ValueError("Plaintext is too long.")
  100. # Step 2a
  101. lHash = self._hashObj.new(self._label).digest()
  102. # Step 2b
  103. ps = b'\x00' * ps_len
  104. # Step 2c
  105. db = lHash + ps + b'\x01' + _copy_bytes(None, None, message)
  106. # Step 2d
  107. ros = self._randfunc(hLen)
  108. # Step 2e
  109. dbMask = self._mgf(ros, k-hLen-1)
  110. # Step 2f
  111. maskedDB = strxor(db, dbMask)
  112. # Step 2g
  113. seedMask = self._mgf(maskedDB, hLen)
  114. # Step 2h
  115. maskedSeed = strxor(ros, seedMask)
  116. # Step 2i
  117. em = b'\x00' + maskedSeed + maskedDB
  118. # Step 3a (OS2IP)
  119. em_int = bytes_to_long(em)
  120. # Step 3b (RSAEP)
  121. m_int = self._key._encrypt(em_int)
  122. # Step 3c (I2OSP)
  123. c = long_to_bytes(m_int, k)
  124. return c
  125. def decrypt(self, ciphertext):
  126. """Decrypt a message with PKCS#1 OAEP.
  127. :param ciphertext: The encrypted message.
  128. :type ciphertext: bytes/bytearray/memoryview
  129. :returns: The original message (plaintext).
  130. :rtype: bytes
  131. :raises ValueError:
  132. if the ciphertext has the wrong length, or if decryption
  133. fails the integrity check (in which case, the decryption
  134. key is probably wrong).
  135. :raises TypeError:
  136. if the RSA key has no private half (i.e. you are trying
  137. to decrypt using a public key).
  138. """
  139. # See 7.1.2 in RFC3447
  140. modBits = Crypto.Util.number.size(self._key.n)
  141. k = ceil_div(modBits, 8) # Convert from bits to bytes
  142. hLen = self._hashObj.digest_size
  143. # Step 1b and 1c
  144. if len(ciphertext) != k or k < hLen+2:
  145. raise ValueError("Ciphertext with incorrect length.")
  146. # Step 2a (O2SIP)
  147. ct_int = bytes_to_long(ciphertext)
  148. # Step 2b (RSADP) and step 2c (I2OSP)
  149. em = self._key._decrypt_to_bytes(ct_int)
  150. # Step 3a
  151. lHash = self._hashObj.new(self._label).digest()
  152. # y must be 0, but we MUST NOT check it here in order not to
  153. # allow attacks like Manger's (http://dl.acm.org/citation.cfm?id=704143)
  154. maskedSeed = em[1:hLen+1]
  155. maskedDB = em[hLen+1:]
  156. # Step 3c
  157. seedMask = self._mgf(maskedDB, hLen)
  158. # Step 3d
  159. seed = strxor(maskedSeed, seedMask)
  160. # Step 3e
  161. dbMask = self._mgf(seed, k-hLen-1)
  162. # Step 3f
  163. db = strxor(maskedDB, dbMask)
  164. # Step 3b + 3g
  165. res = oaep_decode(em, lHash, db)
  166. if res <= 0:
  167. raise ValueError("Incorrect decryption.")
  168. # Step 4
  169. return db[res:]
  170. def new(key, hashAlgo=None, mgfunc=None, label=b'', randfunc=None):
  171. """Return a cipher object :class:`PKCS1OAEP_Cipher`
  172. that can be used to perform PKCS#1 OAEP encryption or decryption.
  173. :param key:
  174. The key object to use to encrypt or decrypt the message.
  175. Decryption is only possible with a private RSA key.
  176. :type key: RSA key object
  177. :param hashAlgo:
  178. The hash function to use. This can be a module under `Crypto.Hash`
  179. or an existing hash object created from any of such modules.
  180. If not specified, `Crypto.Hash.SHA1` is used, matching the RSAES-OAEP
  181. default defined in RFC8017. New protocols should use SHA-256 or a stronger
  182. hash function.
  183. :type hashAlgo: hash object
  184. :param mgfunc:
  185. A mask generation function that accepts two parameters: a string to
  186. use as seed, and the lenth of the mask to generate, in bytes.
  187. If not specified, the standard MGF1 consistent with ``hashAlgo`` is used (a safe choice).
  188. :type mgfunc: callable
  189. :param label:
  190. A label to apply to this particular encryption. If not specified,
  191. an empty string is used. Specifying a label does not improve
  192. security.
  193. :type label: bytes/bytearray/memoryview
  194. :param randfunc:
  195. A function that returns random bytes.
  196. The default is `Random.get_random_bytes`.
  197. :type randfunc: callable
  198. """
  199. if randfunc is None:
  200. randfunc = Random.get_random_bytes
  201. return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label, randfunc)