PKCS1_OAEP.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. """RSA encryption protocol according to PKCS#1 OAEP
  23. See RFC3447__ or the `original RSA Labs specification`__ .
  24. This scheme is more properly called ``RSAES-OAEP``.
  25. As an example, a sender may encrypt a message in this way:
  26. >>> from Crypto.Cipher import PKCS1_OAEP
  27. >>> from Crypto.PublicKey import RSA
  28. >>>
  29. >>> message = 'To be encrypted'
  30. >>> key = RSA.importKey(open('pubkey.der').read())
  31. >>> cipher = PKCS1_OAEP.new(key)
  32. >>> ciphertext = cipher.encrypt(message)
  33. At the receiver side, decryption can be done using the private part of
  34. the RSA key:
  35. >>> key = RSA.importKey(open('privkey.der').read())
  36. >>> cipher = PKCS1_OAP.new(key)
  37. >>> message = cipher.decrypt(ciphertext)
  38. :undocumented: __revision__, __package__
  39. .. __: http://www.ietf.org/rfc/rfc3447.txt
  40. .. __: http://www.rsa.com/rsalabs/node.asp?id=2125.
  41. """
  42. from __future__ import nested_scopes
  43. __revision__ = "$Id$"
  44. __all__ = [ 'new', 'PKCS1OAEP_Cipher' ]
  45. import Crypto.Signature.PKCS1_PSS
  46. import Crypto.Hash.SHA
  47. from Crypto.Util.py3compat import *
  48. import Crypto.Util.number
  49. from Crypto.Util.number import ceil_div
  50. from Crypto.Util.strxor import strxor
  51. class PKCS1OAEP_Cipher:
  52. """This cipher can perform PKCS#1 v1.5 OAEP encryption or decryption."""
  53. def __init__(self, key, hashAlgo, mgfunc, label):
  54. """Initialize this PKCS#1 OAEP cipher object.
  55. :Parameters:
  56. key : an RSA key object
  57. If a private half is given, both encryption and decryption are possible.
  58. If a public half is given, only encryption is possible.
  59. hashAlgo : hash object
  60. The hash function to use. This can be a module under `Crypto.Hash`
  61. or an existing hash object created from any of such modules. If not specified,
  62. `Crypto.Hash.SHA` (that is, SHA-1) is used.
  63. mgfunc : callable
  64. A mask generation function that accepts two parameters: a string to
  65. use as seed, and the lenth of the mask to generate, in bytes.
  66. If not specified, the standard MGF1 is used (a safe choice).
  67. label : string
  68. A label to apply to this particular encryption. If not specified,
  69. an empty string is used. Specifying a label does not improve
  70. security.
  71. :attention: Modify the mask generation function only if you know what you are doing.
  72. Sender and receiver must use the same one.
  73. """
  74. self._key = key
  75. if hashAlgo:
  76. self._hashObj = hashAlgo
  77. else:
  78. self._hashObj = Crypto.Hash.SHA
  79. if mgfunc:
  80. self._mgf = mgfunc
  81. else:
  82. self._mgf = lambda x,y: Crypto.Signature.PKCS1_PSS.MGF1(x,y,self._hashObj)
  83. self._label = label
  84. def can_encrypt(self):
  85. """Return True/1 if this cipher object can be used for encryption."""
  86. return self._key.can_encrypt()
  87. def can_decrypt(self):
  88. """Return True/1 if this cipher object can be used for decryption."""
  89. return self._key.can_decrypt()
  90. def encrypt(self, message):
  91. """Produce the PKCS#1 OAEP encryption of a message.
  92. This function is named ``RSAES-OAEP-ENCRYPT``, and is specified in
  93. section 7.1.1 of RFC3447.
  94. :Parameters:
  95. message : string
  96. The message to encrypt, also known as plaintext. It can be of
  97. variable length, but not longer than the RSA modulus (in bytes)
  98. minus 2, minus twice the hash output size.
  99. :Return: A string, the ciphertext in which the message is encrypted.
  100. It is as long as the RSA modulus (in bytes).
  101. :Raise ValueError:
  102. If the RSA key length is not sufficiently long to deal with the given
  103. message.
  104. """
  105. # TODO: Verify the key is RSA
  106. randFunc = self._key._randfunc
  107. # See 7.1.1 in RFC3447
  108. modBits = Crypto.Util.number.size(self._key.n)
  109. k = ceil_div(modBits,8) # Convert from bits to bytes
  110. hLen = self._hashObj.digest_size
  111. mLen = len(message)
  112. # Step 1b
  113. ps_len = k-mLen-2*hLen-2
  114. if ps_len<0:
  115. raise ValueError("Plaintext is too long.")
  116. # Step 2a
  117. lHash = self._hashObj.new(self._label).digest()
  118. # Step 2b
  119. ps = bchr(0x00)*ps_len
  120. # Step 2c
  121. db = lHash + ps + bchr(0x01) + message
  122. # Step 2d
  123. ros = randFunc(hLen)
  124. # Step 2e
  125. dbMask = self._mgf(ros, k-hLen-1)
  126. # Step 2f
  127. maskedDB = strxor(db, dbMask)
  128. # Step 2g
  129. seedMask = self._mgf(maskedDB, hLen)
  130. # Step 2h
  131. maskedSeed = strxor(ros, seedMask)
  132. # Step 2i
  133. em = bchr(0x00) + maskedSeed + maskedDB
  134. # Step 3a (OS2IP), step 3b (RSAEP), part of step 3c (I2OSP)
  135. m = self._key.encrypt(em, 0)[0]
  136. # Complete step 3c (I2OSP)
  137. c = bchr(0x00)*(k-len(m)) + m
  138. return c
  139. def decrypt(self, ct):
  140. """Decrypt a PKCS#1 OAEP ciphertext.
  141. This function is named ``RSAES-OAEP-DECRYPT``, and is specified in
  142. section 7.1.2 of RFC3447.
  143. :Parameters:
  144. ct : string
  145. The ciphertext that contains the message to recover.
  146. :Return: A string, the original message.
  147. :Raise ValueError:
  148. If the ciphertext length is incorrect, or if the decryption does not
  149. succeed.
  150. :Raise TypeError:
  151. If the RSA key has no private half.
  152. """
  153. # TODO: Verify the key is RSA
  154. # See 7.1.2 in RFC3447
  155. modBits = Crypto.Util.number.size(self._key.n)
  156. k = ceil_div(modBits,8) # Convert from bits to bytes
  157. hLen = self._hashObj.digest_size
  158. # Step 1b and 1c
  159. if len(ct) != k or k<hLen+2:
  160. raise ValueError("Ciphertext with incorrect length.")
  161. # Step 2a (O2SIP), 2b (RSADP), and part of 2c (I2OSP)
  162. m = self._key.decrypt(ct)
  163. # Complete step 2c (I2OSP)
  164. em = bchr(0x00)*(k-len(m)) + m
  165. # Step 3a
  166. lHash = self._hashObj.new(self._label).digest()
  167. # Step 3b
  168. y = em[0]
  169. # y must be 0, but we MUST NOT check it here in order not to
  170. # allow attacks like Manger's (http://dl.acm.org/citation.cfm?id=704143)
  171. maskedSeed = em[1:hLen+1]
  172. maskedDB = em[hLen+1:]
  173. # Step 3c
  174. seedMask = self._mgf(maskedDB, hLen)
  175. # Step 3d
  176. seed = strxor(maskedSeed, seedMask)
  177. # Step 3e
  178. dbMask = self._mgf(seed, k-hLen-1)
  179. # Step 3f
  180. db = strxor(maskedDB, dbMask)
  181. # Step 3g
  182. valid = 1
  183. one = db[hLen:].find(bchr(0x01))
  184. lHash1 = db[:hLen]
  185. if lHash1!=lHash:
  186. valid = 0
  187. if one<0:
  188. valid = 0
  189. if bord(y)!=0:
  190. valid = 0
  191. if not valid:
  192. raise ValueError("Incorrect decryption.")
  193. # Step 4
  194. return db[hLen+one+1:]
  195. def new(key, hashAlgo=None, mgfunc=None, label=b('')):
  196. """Return a cipher object `PKCS1OAEP_Cipher` that can be used to perform PKCS#1 OAEP encryption or decryption.
  197. :Parameters:
  198. key : RSA key object
  199. The key to use to encrypt or decrypt the message. This is a `Crypto.PublicKey.RSA` object.
  200. Decryption is only possible if *key* is a private RSA key.
  201. hashAlgo : hash object
  202. The hash function to use. This can be a module under `Crypto.Hash`
  203. or an existing hash object created from any of such modules. If not specified,
  204. `Crypto.Hash.SHA` (that is, SHA-1) is used.
  205. mgfunc : callable
  206. A mask generation function that accepts two parameters: a string to
  207. use as seed, and the lenth of the mask to generate, in bytes.
  208. If not specified, the standard MGF1 is used (a safe choice).
  209. label : string
  210. A label to apply to this particular encryption. If not specified,
  211. an empty string is used. Specifying a label does not improve
  212. security.
  213. :attention: Modify the mask generation function only if you know what you are doing.
  214. Sender and receiver must use the same one.
  215. """
  216. return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label)