test_CFB.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. import unittest
  31. from binascii import unhexlify
  32. from Crypto.SelfTest.loader import load_test_vectors
  33. from Crypto.SelfTest.st_common import list_test_cases
  34. from Crypto.Util.py3compat import tobytes, is_string
  35. from Crypto.Cipher import AES, DES3, DES
  36. from Crypto.Hash import SHAKE128
  37. from Crypto.SelfTest.Cipher.test_CBC import BlockChainingTests
  38. def get_tag_random(tag, length):
  39. return SHAKE128.new(data=tobytes(tag)).read(length)
  40. class CfbTests(BlockChainingTests):
  41. aes_mode = AES.MODE_CFB
  42. des3_mode = DES3.MODE_CFB
  43. # Redefine test_unaligned_data_128/64
  44. def test_unaligned_data_128(self):
  45. plaintexts = [ b"7777777" ] * 100
  46. cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=8)
  47. ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
  48. cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=8)
  49. self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
  50. cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=128)
  51. ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
  52. cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=128)
  53. self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
  54. def test_unaligned_data_64(self):
  55. plaintexts = [ b"7777777" ] * 100
  56. cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8)
  57. ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
  58. cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8)
  59. self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
  60. cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64)
  61. ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
  62. cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64)
  63. self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
  64. # Extra
  65. def test_segment_size_128(self):
  66. for bits in range(8, 129, 8):
  67. cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128,
  68. segment_size=bits)
  69. for bits in 0, 7, 9, 127, 129:
  70. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CFB,
  71. self.iv_128,
  72. segment_size=bits)
  73. def test_segment_size_64(self):
  74. for bits in range(8, 65, 8):
  75. cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64,
  76. segment_size=bits)
  77. for bits in 0, 7, 9, 63, 65:
  78. self.assertRaises(ValueError, DES3.new, self.key_192, AES.MODE_CFB,
  79. self.iv_64,
  80. segment_size=bits)
  81. class NistCfbVectors(unittest.TestCase):
  82. def _do_kat_aes_test(self, file_name, segment_size):
  83. test_vectors = load_test_vectors(("Cipher", "AES"),
  84. file_name,
  85. "AES CFB%d KAT" % segment_size,
  86. { "count" : lambda x: int(x) } )
  87. if test_vectors is None:
  88. return
  89. direction = None
  90. for tv in test_vectors:
  91. # The test vector file contains some directive lines
  92. if is_string(tv):
  93. direction = tv
  94. continue
  95. self.description = tv.desc
  96. cipher = AES.new(tv.key, AES.MODE_CFB, tv.iv,
  97. segment_size=segment_size)
  98. if direction == "[ENCRYPT]":
  99. self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
  100. elif direction == "[DECRYPT]":
  101. self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
  102. else:
  103. assert False
  104. # See Section 6.4.5 in AESAVS
  105. def _do_mct_aes_test(self, file_name, segment_size):
  106. test_vectors = load_test_vectors(("Cipher", "AES"),
  107. file_name,
  108. "AES CFB%d Montecarlo" % segment_size,
  109. { "count" : lambda x: int(x) } )
  110. if test_vectors is None:
  111. return
  112. assert(segment_size in (8, 128))
  113. direction = None
  114. for tv in test_vectors:
  115. # The test vector file contains some directive lines
  116. if is_string(tv):
  117. direction = tv
  118. continue
  119. self.description = tv.desc
  120. cipher = AES.new(tv.key, AES.MODE_CFB, tv.iv,
  121. segment_size=segment_size)
  122. def get_input(input_text, output_seq, j):
  123. # CFB128
  124. if segment_size == 128:
  125. if j >= 2:
  126. return output_seq[-2]
  127. return [input_text, tv.iv][j]
  128. # CFB8
  129. if j == 0:
  130. return input_text
  131. elif j <= 16:
  132. return tv.iv[j - 1:j]
  133. return output_seq[j - 17]
  134. if direction == '[ENCRYPT]':
  135. cts = []
  136. for j in range(1000):
  137. plaintext = get_input(tv.plaintext, cts, j)
  138. cts.append(cipher.encrypt(plaintext))
  139. self.assertEqual(cts[-1], tv.ciphertext)
  140. elif direction == '[DECRYPT]':
  141. pts = []
  142. for j in range(1000):
  143. ciphertext = get_input(tv.ciphertext, pts, j)
  144. pts.append(cipher.decrypt(ciphertext))
  145. self.assertEqual(pts[-1], tv.plaintext)
  146. else:
  147. assert False
  148. def _do_tdes_test(self, file_name, segment_size):
  149. test_vectors = load_test_vectors(("Cipher", "TDES"),
  150. file_name,
  151. "TDES CFB%d KAT" % segment_size,
  152. { "count" : lambda x: int(x) } )
  153. if test_vectors is None:
  154. return
  155. direction = None
  156. for tv in test_vectors:
  157. # The test vector file contains some directive lines
  158. if is_string(tv):
  159. direction = tv
  160. continue
  161. self.description = tv.desc
  162. if hasattr(tv, "keys"):
  163. cipher = DES.new(tv.keys, DES.MODE_CFB, tv.iv,
  164. segment_size=segment_size)
  165. else:
  166. if tv.key1 != tv.key3:
  167. key = tv.key1 + tv.key2 + tv.key3 # Option 3
  168. else:
  169. key = tv.key1 + tv.key2 # Option 2
  170. cipher = DES3.new(key, DES3.MODE_CFB, tv.iv,
  171. segment_size=segment_size)
  172. if direction == "[ENCRYPT]":
  173. self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
  174. elif direction == "[DECRYPT]":
  175. self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
  176. else:
  177. assert False
  178. # Create one test method per file
  179. nist_aes_kat_mmt_files = (
  180. # KAT
  181. "CFB?GFSbox128.rsp",
  182. "CFB?GFSbox192.rsp",
  183. "CFB?GFSbox256.rsp",
  184. "CFB?KeySbox128.rsp",
  185. "CFB?KeySbox192.rsp",
  186. "CFB?KeySbox256.rsp",
  187. "CFB?VarKey128.rsp",
  188. "CFB?VarKey192.rsp",
  189. "CFB?VarKey256.rsp",
  190. "CFB?VarTxt128.rsp",
  191. "CFB?VarTxt192.rsp",
  192. "CFB?VarTxt256.rsp",
  193. # MMT
  194. "CFB?MMT128.rsp",
  195. "CFB?MMT192.rsp",
  196. "CFB?MMT256.rsp",
  197. )
  198. nist_aes_mct_files = (
  199. "CFB?MCT128.rsp",
  200. "CFB?MCT192.rsp",
  201. "CFB?MCT256.rsp",
  202. )
  203. for file_gen_name in nist_aes_kat_mmt_files:
  204. for bits in "8", "128":
  205. file_name = file_gen_name.replace("?", bits)
  206. def new_func(self, file_name=file_name, bits=bits):
  207. self._do_kat_aes_test(file_name, int(bits))
  208. setattr(NistCfbVectors, "test_AES_" + file_name, new_func)
  209. for file_gen_name in nist_aes_mct_files:
  210. for bits in "8", "128":
  211. file_name = file_gen_name.replace("?", bits)
  212. def new_func(self, file_name=file_name, bits=bits):
  213. self._do_mct_aes_test(file_name, int(bits))
  214. setattr(NistCfbVectors, "test_AES_" + file_name, new_func)
  215. del file_name, new_func
  216. nist_tdes_files = (
  217. "TCFB?MMT2.rsp", # 2TDES
  218. "TCFB?MMT3.rsp", # 3TDES
  219. "TCFB?invperm.rsp", # Single DES
  220. "TCFB?permop.rsp",
  221. "TCFB?subtab.rsp",
  222. "TCFB?varkey.rsp",
  223. "TCFB?vartext.rsp",
  224. )
  225. for file_gen_name in nist_tdes_files:
  226. for bits in "8", "64":
  227. file_name = file_gen_name.replace("?", bits)
  228. def new_func(self, file_name=file_name, bits=bits):
  229. self._do_tdes_test(file_name, int(bits))
  230. setattr(NistCfbVectors, "test_TDES_" + file_name, new_func)
  231. # END OF NIST CBC TEST VECTORS
  232. class SP800TestVectors(unittest.TestCase):
  233. """Class exercising the CFB test vectors found in Section F.3
  234. of NIST SP 800-3A"""
  235. def test_aes_128_cfb8(self):
  236. plaintext = '6bc1bee22e409f96e93d7e117393172aae2d'
  237. ciphertext = '3b79424c9c0dd436bace9e0ed4586a4f32b9'
  238. key = '2b7e151628aed2a6abf7158809cf4f3c'
  239. iv = '000102030405060708090a0b0c0d0e0f'
  240. key = unhexlify(key)
  241. iv = unhexlify(iv)
  242. plaintext = unhexlify(plaintext)
  243. ciphertext = unhexlify(ciphertext)
  244. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=8)
  245. self.assertEqual(cipher.encrypt(plaintext), ciphertext)
  246. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=8)
  247. self.assertEqual(cipher.decrypt(ciphertext), plaintext)
  248. def test_aes_192_cfb8(self):
  249. plaintext = '6bc1bee22e409f96e93d7e117393172aae2d'
  250. ciphertext = 'cda2521ef0a905ca44cd057cbf0d47a0678a'
  251. key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
  252. iv = '000102030405060708090a0b0c0d0e0f'
  253. key = unhexlify(key)
  254. iv = unhexlify(iv)
  255. plaintext = unhexlify(plaintext)
  256. ciphertext = unhexlify(ciphertext)
  257. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=8)
  258. self.assertEqual(cipher.encrypt(plaintext), ciphertext)
  259. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=8)
  260. self.assertEqual(cipher.decrypt(ciphertext), plaintext)
  261. def test_aes_256_cfb8(self):
  262. plaintext = '6bc1bee22e409f96e93d7e117393172aae2d'
  263. ciphertext = 'dc1f1a8520a64db55fcc8ac554844e889700'
  264. key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
  265. iv = '000102030405060708090a0b0c0d0e0f'
  266. key = unhexlify(key)
  267. iv = unhexlify(iv)
  268. plaintext = unhexlify(plaintext)
  269. ciphertext = unhexlify(ciphertext)
  270. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=8)
  271. self.assertEqual(cipher.encrypt(plaintext), ciphertext)
  272. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=8)
  273. self.assertEqual(cipher.decrypt(ciphertext), plaintext)
  274. def test_aes_128_cfb128(self):
  275. plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
  276. 'ae2d8a571e03ac9c9eb76fac45af8e51' +\
  277. '30c81c46a35ce411e5fbc1191a0a52ef' +\
  278. 'f69f2445df4f9b17ad2b417be66c3710'
  279. ciphertext = '3b3fd92eb72dad20333449f8e83cfb4a' +\
  280. 'c8a64537a0b3a93fcde3cdad9f1ce58b' +\
  281. '26751f67a3cbb140b1808cf187a4f4df' +\
  282. 'c04b05357c5d1c0eeac4c66f9ff7f2e6'
  283. key = '2b7e151628aed2a6abf7158809cf4f3c'
  284. iv = '000102030405060708090a0b0c0d0e0f'
  285. key = unhexlify(key)
  286. iv = unhexlify(iv)
  287. plaintext = unhexlify(plaintext)
  288. ciphertext = unhexlify(ciphertext)
  289. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
  290. self.assertEqual(cipher.encrypt(plaintext), ciphertext)
  291. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
  292. self.assertEqual(cipher.decrypt(ciphertext), plaintext)
  293. def test_aes_192_cfb128(self):
  294. plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
  295. 'ae2d8a571e03ac9c9eb76fac45af8e51' +\
  296. '30c81c46a35ce411e5fbc1191a0a52ef' +\
  297. 'f69f2445df4f9b17ad2b417be66c3710'
  298. ciphertext = 'cdc80d6fddf18cab34c25909c99a4174' +\
  299. '67ce7f7f81173621961a2b70171d3d7a' +\
  300. '2e1e8a1dd59b88b1c8e60fed1efac4c9' +\
  301. 'c05f9f9ca9834fa042ae8fba584b09ff'
  302. key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
  303. iv = '000102030405060708090a0b0c0d0e0f'
  304. key = unhexlify(key)
  305. iv = unhexlify(iv)
  306. plaintext = unhexlify(plaintext)
  307. ciphertext = unhexlify(ciphertext)
  308. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
  309. self.assertEqual(cipher.encrypt(plaintext), ciphertext)
  310. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
  311. self.assertEqual(cipher.decrypt(ciphertext), plaintext)
  312. def test_aes_256_cfb128(self):
  313. plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
  314. 'ae2d8a571e03ac9c9eb76fac45af8e51' +\
  315. '30c81c46a35ce411e5fbc1191a0a52ef' +\
  316. 'f69f2445df4f9b17ad2b417be66c3710'
  317. ciphertext = 'dc7e84bfda79164b7ecd8486985d3860' +\
  318. '39ffed143b28b1c832113c6331e5407b' +\
  319. 'df10132415e54b92a13ed0a8267ae2f9' +\
  320. '75a385741ab9cef82031623d55b1e471'
  321. key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
  322. iv = '000102030405060708090a0b0c0d0e0f'
  323. key = unhexlify(key)
  324. iv = unhexlify(iv)
  325. plaintext = unhexlify(plaintext)
  326. ciphertext = unhexlify(ciphertext)
  327. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
  328. self.assertEqual(cipher.encrypt(plaintext), ciphertext)
  329. cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
  330. self.assertEqual(cipher.decrypt(ciphertext), plaintext)
  331. def get_tests(config={}):
  332. tests = []
  333. tests += list_test_cases(CfbTests)
  334. if config.get('slow_tests'):
  335. tests += list_test_cases(NistCfbVectors)
  336. tests += list_test_cases(SP800TestVectors)
  337. return tests
  338. if __name__ == '__main__':
  339. suite = lambda: unittest.TestSuite(get_tests())
  340. unittest.main(defaultTest='suite')