blockalgo.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/blockalgo.py
  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. """Module with definitions common to all block ciphers."""
  23. import sys
  24. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  25. from Crypto.Util.py21compat import *
  26. from Crypto.Util.py3compat import *
  27. #: *Electronic Code Book (ECB)*.
  28. #: This is the simplest encryption mode. Each of the plaintext blocks
  29. #: is directly encrypted into a ciphertext block, independently of
  30. #: any other block. This mode exposes frequency of symbols
  31. #: in your plaintext. Other modes (e.g. *CBC*) should be used instead.
  32. #:
  33. #: See `NIST SP800-38A`_ , Section 6.1 .
  34. #:
  35. #: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  36. MODE_ECB = 1
  37. #: *Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends
  38. #: on the current and all previous plaintext blocks. An Initialization Vector
  39. #: (*IV*) is required.
  40. #:
  41. #: The *IV* is a data block to be transmitted to the receiver.
  42. #: The *IV* can be made public, but it must be authenticated by the receiver and
  43. #: it should be picked randomly.
  44. #:
  45. #: See `NIST SP800-38A`_ , Section 6.2 .
  46. #:
  47. #: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  48. MODE_CBC = 2
  49. #: *Cipher FeedBack (CFB)*. This mode is similar to CBC, but it transforms
  50. #: the underlying block cipher into a stream cipher. Plaintext and ciphertext
  51. #: are processed in *segments* of **s** bits. The mode is therefore sometimes
  52. #: labelled **s**-bit CFB. An Initialization Vector (*IV*) is required.
  53. #:
  54. #: When encrypting, each ciphertext segment contributes to the encryption of
  55. #: the next plaintext segment.
  56. #:
  57. #: This *IV* is a data block to be transmitted to the receiver.
  58. #: The *IV* can be made public, but it should be picked randomly.
  59. #: Reusing the same *IV* for encryptions done with the same key lead to
  60. #: catastrophic cryptographic failures.
  61. #:
  62. #: See `NIST SP800-38A`_ , Section 6.3 .
  63. #:
  64. #: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  65. MODE_CFB = 3
  66. #: This mode should not be used.
  67. MODE_PGP = 4
  68. #: *Output FeedBack (OFB)*. This mode is very similar to CBC, but it
  69. #: transforms the underlying block cipher into a stream cipher.
  70. #: The keystream is the iterated block encryption of an Initialization Vector (*IV*).
  71. #:
  72. #: The *IV* is a data block to be transmitted to the receiver.
  73. #: The *IV* can be made public, but it should be picked randomly.
  74. #:
  75. #: Reusing the same *IV* for encryptions done with the same key lead to
  76. #: catastrophic cryptograhic failures.
  77. #:
  78. #: See `NIST SP800-38A`_ , Section 6.4 .
  79. #:
  80. #: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  81. MODE_OFB = 5
  82. #: *CounTeR (CTR)*. This mode is very similar to ECB, in that
  83. #: encryption of one block is done independently of all other blocks.
  84. #: Unlike ECB, the block *position* contributes to the encryption and no
  85. #: information leaks about symbol frequency.
  86. #:
  87. #: Each message block is associated to a *counter* which must be unique
  88. #: across all messages that get encrypted with the same key (not just within
  89. #: the same message). The counter is as big as the block size.
  90. #:
  91. #: Counters can be generated in several ways. The most straightword one is
  92. #: to choose an *initial counter block* (which can be made public, similarly
  93. #: to the *IV* for the other modes) and increment its lowest **m** bits by
  94. #: one (modulo *2^m*) for each block. In most cases, **m** is chosen to be half
  95. #: the block size.
  96. #:
  97. #: Reusing the same *initial counter block* for encryptions done with the same
  98. #: key lead to catastrophic cryptograhic failures.
  99. #:
  100. #: See `NIST SP800-38A`_ , Section 6.5 (for the mode) and Appendix B (for how
  101. #: to manage the *initial counter block*).
  102. #:
  103. #: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  104. MODE_CTR = 6
  105. #: OpenPGP. This mode is a variant of CFB, and it is only used in PGP and OpenPGP_ applications.
  106. #: An Initialization Vector (*IV*) is required.
  107. #:
  108. #: Unlike CFB, the IV is not transmitted to the receiver. Instead, the *encrypted* IV is.
  109. #: The IV is a random data block. Two of its bytes are duplicated to act as a checksum
  110. #: for the correctness of the key. The encrypted IV is therefore 2 bytes longer than
  111. #: the clean IV.
  112. #:
  113. #: .. _OpenPGP: http://tools.ietf.org/html/rfc4880
  114. MODE_OPENPGP = 7
  115. def _getParameter(name, index, args, kwargs, default=None):
  116. """Find a parameter in tuple and dictionary arguments a function receives"""
  117. param = kwargs.get(name)
  118. if len(args)>index:
  119. if param:
  120. raise ValueError("Parameter '%s' is specified twice" % name)
  121. param = args[index]
  122. return param or default
  123. class BlockAlgo:
  124. """Class modelling an abstract block cipher."""
  125. def __init__(self, factory, key, *args, **kwargs):
  126. self.mode = _getParameter('mode', 0, args, kwargs, default=MODE_ECB)
  127. self.block_size = factory.block_size
  128. if self.mode != MODE_OPENPGP:
  129. self._cipher = factory.new(key, *args, **kwargs)
  130. self.IV = self._cipher.IV
  131. else:
  132. # OPENPGP mode. For details, see 13.9 in RCC4880.
  133. #
  134. # A few members are specifically created for this mode:
  135. # - _encrypted_iv, set in this constructor
  136. # - _done_first_block, set to True after the first encryption
  137. # - _done_last_block, set to True after a partial block is processed
  138. self._done_first_block = False
  139. self._done_last_block = False
  140. self.IV = _getParameter('iv', 1, args, kwargs)
  141. if not self.IV:
  142. raise ValueError("MODE_OPENPGP requires an IV")
  143. # Instantiate a temporary cipher to process the IV
  144. IV_cipher = factory.new(key, MODE_CFB,
  145. b('\x00')*self.block_size, # IV for CFB
  146. segment_size=self.block_size*8)
  147. # The cipher will be used for...
  148. if len(self.IV) == self.block_size:
  149. # ... encryption
  150. self._encrypted_IV = IV_cipher.encrypt(
  151. self.IV + self.IV[-2:] + # Plaintext
  152. b('\x00')*(self.block_size-2) # Padding
  153. )[:self.block_size+2]
  154. elif len(self.IV) == self.block_size+2:
  155. # ... decryption
  156. self._encrypted_IV = self.IV
  157. self.IV = IV_cipher.decrypt(self.IV + # Ciphertext
  158. b('\x00')*(self.block_size-2) # Padding
  159. )[:self.block_size+2]
  160. if self.IV[-2:] != self.IV[-4:-2]:
  161. raise ValueError("Failed integrity check for OPENPGP IV")
  162. self.IV = self.IV[:-2]
  163. else:
  164. raise ValueError("Length of IV must be %d or %d bytes for MODE_OPENPGP"
  165. % (self.block_size, self.block_size+2))
  166. # Instantiate the cipher for the real PGP data
  167. self._cipher = factory.new(key, MODE_CFB,
  168. self._encrypted_IV[-self.block_size:],
  169. segment_size=self.block_size*8)
  170. def encrypt(self, plaintext):
  171. """Encrypt data with the key and the parameters set at initialization.
  172. The cipher object is stateful; encryption of a long block
  173. of data can be broken up in two or more calls to `encrypt()`.
  174. That is, the statement:
  175. >>> c.encrypt(a) + c.encrypt(b)
  176. is always equivalent to:
  177. >>> c.encrypt(a+b)
  178. That also means that you cannot reuse an object for encrypting
  179. or decrypting other data with the same key.
  180. This function does not perform any padding.
  181. - For `MODE_ECB`, `MODE_CBC`, and `MODE_OFB`, *plaintext* length
  182. (in bytes) must be a multiple of *block_size*.
  183. - For `MODE_CFB`, *plaintext* length (in bytes) must be a multiple
  184. of *segment_size*/8.
  185. - For `MODE_CTR`, *plaintext* can be of any length.
  186. - For `MODE_OPENPGP`, *plaintext* must be a multiple of *block_size*,
  187. unless it is the last chunk of the message.
  188. :Parameters:
  189. plaintext : byte string
  190. The piece of data to encrypt.
  191. :Return:
  192. the encrypted data, as a byte string. It is as long as
  193. *plaintext* with one exception: when encrypting the first message
  194. chunk with `MODE_OPENPGP`, the encypted IV is prepended to the
  195. returned ciphertext.
  196. """
  197. if self.mode == MODE_OPENPGP:
  198. padding_length = (self.block_size - len(plaintext) % self.block_size) % self.block_size
  199. if padding_length>0:
  200. # CFB mode requires ciphertext to have length multiple of block size,
  201. # but PGP mode allows the last block to be shorter
  202. if self._done_last_block:
  203. raise ValueError("Only the last chunk is allowed to have length not multiple of %d bytes",
  204. self.block_size)
  205. self._done_last_block = True
  206. padded = plaintext + b('\x00')*padding_length
  207. res = self._cipher.encrypt(padded)[:len(plaintext)]
  208. else:
  209. res = self._cipher.encrypt(plaintext)
  210. if not self._done_first_block:
  211. res = self._encrypted_IV + res
  212. self._done_first_block = True
  213. return res
  214. return self._cipher.encrypt(plaintext)
  215. def decrypt(self, ciphertext):
  216. """Decrypt data with the key and the parameters set at initialization.
  217. The cipher object is stateful; decryption of a long block
  218. of data can be broken up in two or more calls to `decrypt()`.
  219. That is, the statement:
  220. >>> c.decrypt(a) + c.decrypt(b)
  221. is always equivalent to:
  222. >>> c.decrypt(a+b)
  223. That also means that you cannot reuse an object for encrypting
  224. or decrypting other data with the same key.
  225. This function does not perform any padding.
  226. - For `MODE_ECB`, `MODE_CBC`, and `MODE_OFB`, *ciphertext* length
  227. (in bytes) must be a multiple of *block_size*.
  228. - For `MODE_CFB`, *ciphertext* length (in bytes) must be a multiple
  229. of *segment_size*/8.
  230. - For `MODE_CTR`, *ciphertext* can be of any length.
  231. - For `MODE_OPENPGP`, *plaintext* must be a multiple of *block_size*,
  232. unless it is the last chunk of the message.
  233. :Parameters:
  234. ciphertext : byte string
  235. The piece of data to decrypt.
  236. :Return: the decrypted data (byte string, as long as *ciphertext*).
  237. """
  238. if self.mode == MODE_OPENPGP:
  239. padding_length = (self.block_size - len(ciphertext) % self.block_size) % self.block_size
  240. if padding_length>0:
  241. # CFB mode requires ciphertext to have length multiple of block size,
  242. # but PGP mode allows the last block to be shorter
  243. if self._done_last_block:
  244. raise ValueError("Only the last chunk is allowed to have length not multiple of %d bytes",
  245. self.block_size)
  246. self._done_last_block = True
  247. padded = ciphertext + b('\x00')*padding_length
  248. res = self._cipher.decrypt(padded)[:len(ciphertext)]
  249. else:
  250. res = self._cipher.decrypt(ciphertext)
  251. return res
  252. return self._cipher.decrypt(ciphertext)