speck.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. from __future__ import print_function
  2. class SpeckCipher(object):
  3. """Speck Block Cipher Object"""
  4. # valid cipher configurations stored:
  5. # block_size:{key_size:number_rounds}
  6. __valid_setups = {32: {64: 22},
  7. 48: {72: 22, 96: 23},
  8. 64: {96: 26, 128: 27},
  9. 96: {96: 28, 144: 29},
  10. 128: {128: 32, 192: 33, 256: 34}}
  11. __valid_modes = ['ECB', 'CTR', 'CBC', 'PCBC', 'CFB', 'OFB']
  12. def encrypt_round(self, x, y, k):
  13. """Complete One Round of Feistel Operation"""
  14. rs_x = ((x << (self.word_size - self.alpha_shift)) + (x >> self.alpha_shift)) & self.mod_mask
  15. add_sxy = (rs_x + y) & self.mod_mask
  16. new_x = k ^ add_sxy
  17. ls_y = ((y >> (self.word_size - self.beta_shift)) + (y << self.beta_shift)) & self.mod_mask
  18. new_y = new_x ^ ls_y
  19. return new_x, new_y
  20. def decrypt_round(self, x, y, k):
  21. """Complete One Round of Inverse Feistel Operation"""
  22. xor_xy = x ^ y
  23. new_y = ((xor_xy << (self.word_size - self.beta_shift)) + (xor_xy >> self.beta_shift)) & self.mod_mask
  24. xor_xk = x ^ k
  25. msub = ((xor_xk - new_y) + self.mod_mask_sub) % self.mod_mask_sub
  26. new_x = ((msub >> (self.word_size - self.alpha_shift)) + (msub << self.alpha_shift)) & self.mod_mask
  27. return new_x, new_y
  28. def __init__(self, key, key_size=128, block_size=128, mode='ECB', init=0, counter=0):
  29. # Setup block/word size
  30. try:
  31. self.possible_setups = self.__valid_setups[block_size]
  32. self.block_size = block_size
  33. self.word_size = self.block_size >> 1
  34. except KeyError:
  35. print('Invalid block size!')
  36. print('Please use one of the following block sizes:', [x for x in self.__valid_setups.keys()])
  37. raise
  38. # Setup Number of Rounds and Key Size
  39. try:
  40. self.rounds = self.possible_setups[key_size]
  41. self.key_size = key_size
  42. except KeyError:
  43. print('Invalid key size for selected block size!!')
  44. print('Please use one of the following key sizes:', [x for x in self.possible_setups.keys()])
  45. raise
  46. # Create Properly Sized bit mask for truncating addition and left shift outputs
  47. self.mod_mask = (2 ** self.word_size) - 1
  48. # Mod mask for modular subtraction
  49. self.mod_mask_sub = (2 ** self.word_size)
  50. # Setup Circular Shift Parameters
  51. if self.block_size == 32:
  52. self.beta_shift = 2
  53. self.alpha_shift = 7
  54. else:
  55. self.beta_shift = 3
  56. self.alpha_shift = 8
  57. # Parse the given iv and truncate it to the block length
  58. try:
  59. self.iv = init & ((2 ** self.block_size) - 1)
  60. self.iv_upper = self.iv >> self.word_size
  61. self.iv_lower = self.iv & self.mod_mask
  62. except (ValueError, TypeError):
  63. print('Invalid IV Value!')
  64. print('Please Provide IV as int')
  65. raise
  66. # Parse the given Counter and truncate it to the block length
  67. try:
  68. self.counter = counter & ((2 ** self.block_size) - 1)
  69. except (ValueError, TypeError):
  70. print('Invalid Counter Value!')
  71. print('Please Provide Counter as int')
  72. raise
  73. # Check Cipher Mode
  74. try:
  75. position = self.__valid_modes.index(mode)
  76. self.mode = self.__valid_modes[position]
  77. except ValueError:
  78. print('Invalid cipher mode!')
  79. print('Please use one of the following block cipher modes:', self.__valid_modes)
  80. raise
  81. # Parse the given key and truncate it to the key length
  82. try:
  83. self.key = key & ((2 ** self.key_size) - 1)
  84. except (ValueError, TypeError):
  85. print('Invalid Key Value!')
  86. print('Please Provide Key as int')
  87. raise
  88. # Pre-compile key schedule
  89. self.key_schedule = [self.key & self.mod_mask]
  90. l_schedule = [(self.key >> (x * self.word_size)) & self.mod_mask for x in
  91. range(1, self.key_size // self.word_size)]
  92. for x in range(self.rounds - 1):
  93. new_l_k = self.encrypt_round(l_schedule[x], self.key_schedule[x], x)
  94. l_schedule.append(new_l_k[0])
  95. self.key_schedule.append(new_l_k[1])
  96. print(self.key_schedule)
  97. def encrypt(self, plaintext):
  98. try:
  99. b = (plaintext >> self.word_size) & self.mod_mask
  100. a = plaintext & self.mod_mask
  101. except TypeError:
  102. print('Invalid plaintext!')
  103. print('Please provide plaintext as int')
  104. raise
  105. if self.mode == 'ECB':
  106. b, a = self.encrypt_function(b, a)
  107. elif self.mode == 'CTR':
  108. true_counter = self.iv + self.counter
  109. d = (true_counter >> self.word_size) & self.mod_mask
  110. c = true_counter & self.mod_mask
  111. d, c = self.encrypt_function(d, c)
  112. b ^= d
  113. a ^= c
  114. self.counter += 1
  115. elif self.mode == 'CBC':
  116. b ^= self.iv_upper
  117. a ^= self.iv_lower
  118. b, a = self.encrypt_function(b, a)
  119. self.iv_upper = b
  120. self.iv_lower = a
  121. self.iv = (b << self.word_size) + a
  122. elif self.mode == 'PCBC':
  123. f, e = b, a
  124. b ^= self.iv_upper
  125. a ^= self.iv_lower
  126. b, a = self.encrypt_function(b, a)
  127. self.iv_upper = (b ^ f)
  128. self.iv_lower = (a ^ e)
  129. self.iv = (self.iv_upper << self.word_size) + self.iv_lower
  130. elif self.mode == 'CFB':
  131. d = self.iv_upper
  132. c = self.iv_lower
  133. d, c = self.encrypt_function(d, c)
  134. b ^= d
  135. a ^= c
  136. self.iv_upper = b
  137. self.iv_lower = a
  138. self.iv = (b << self.word_size) + a
  139. elif self.mode == 'OFB':
  140. d = self.iv_upper
  141. c = self.iv_lower
  142. d, c = self.encrypt_function(d, c)
  143. self.iv_upper = d
  144. self.iv_lower = c
  145. self.iv = (d << self.word_size) + c
  146. b ^= d
  147. a ^= c
  148. ciphertext = (b << self.word_size) + a
  149. return ciphertext
  150. def decrypt(self, ciphertext):
  151. try:
  152. b = (ciphertext >> self.word_size) & self.mod_mask
  153. a = ciphertext & self.mod_mask
  154. except TypeError:
  155. print('Invalid ciphertext!')
  156. print('Please provide plaintext as int')
  157. raise
  158. if self.mode == 'ECB':
  159. b, a = self.decrypt_function(b, a)
  160. elif self.mode == 'CTR':
  161. true_counter = self.iv + self.counter
  162. d = (true_counter >> self.word_size) & self.mod_mask
  163. c = true_counter & self.mod_mask
  164. d, c = self.encrypt_function(d, c)
  165. b ^= d
  166. a ^= c
  167. self.counter += 1
  168. elif self.mode == 'CBC':
  169. f, e = b, a
  170. b, a = self.decrypt_function(b, a)
  171. b ^= self.iv_upper
  172. a ^= self.iv_lower
  173. self.iv_upper = f
  174. self.iv_lower = e
  175. self.iv = (f << self.word_size) + e
  176. elif self.mode == 'PCBC':
  177. f, e = b, a
  178. b, a = self.decrypt_function(b, a)
  179. b ^= self.iv_upper
  180. a ^= self.iv_lower
  181. self.iv_upper = (b ^ f)
  182. self.iv_lower = (a ^ e)
  183. self.iv = (self.iv_upper << self.word_size) + self.iv_lower
  184. elif self.mode == 'CFB':
  185. d = self.iv_upper
  186. c = self.iv_lower
  187. self.iv_upper = b
  188. self.iv_lower = a
  189. self.iv = (b << self.word_size) + a
  190. d, c = self.encrypt_function(d, c)
  191. b ^= d
  192. a ^= c
  193. elif self.mode == 'OFB':
  194. d = self.iv_upper
  195. c = self.iv_lower
  196. d, c = self.encrypt_function(d, c)
  197. self.iv_upper = d
  198. self.iv_lower = c
  199. self.iv = (d << self.word_size) + c
  200. b ^= d
  201. a ^= c
  202. plaintext = (b << self.word_size) + a
  203. return plaintext
  204. def encrypt_function(self, upper_word, lower_word):
  205. x = upper_word
  206. y = lower_word
  207. # Run Encryption Steps For Appropriate Number of Rounds
  208. for k in self.key_schedule:
  209. rs_x = ((x << (self.word_size - self.alpha_shift)) + (x >> self.alpha_shift)) & self.mod_mask
  210. add_sxy = (rs_x + y) & self.mod_mask
  211. x = k ^ add_sxy
  212. ls_y = ((y >> (self.word_size - self.beta_shift)) + (y << self.beta_shift)) & self.mod_mask
  213. y = x ^ ls_y
  214. return x,y
  215. def decrypt_function(self, upper_word, lower_word):
  216. x = upper_word
  217. y = lower_word
  218. # Run Encryption Steps For Appropriate Number of Rounds
  219. for k in reversed(self.key_schedule):
  220. xor_xy = x ^ y
  221. y = ((xor_xy << (self.word_size - self.beta_shift)) + (xor_xy >> self.beta_shift)) & self.mod_mask
  222. xor_xk = x ^ k
  223. msub = ((xor_xk - y) + self.mod_mask_sub) % self.mod_mask_sub
  224. x = ((msub >> (self.word_size - self.alpha_shift)) + (msub << self.alpha_shift)) & self.mod_mask
  225. return x,y
  226. def update_iv(self, new_iv=None):
  227. if new_iv:
  228. try:
  229. self.iv = new_iv & ((2 ** self.block_size) - 1)
  230. self.iv_upper = self.iv >> self.word_size
  231. self.iv_lower = self.iv & self.mod_mask
  232. except TypeError:
  233. print('Invalid Initialization Vector!')
  234. print('Please provide IV as int')
  235. raise
  236. return self.iv
  237. if __name__ == "__main__":
  238. #cipher = SpeckCipher(0x1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100, 256, 128, 'ECB')
  239. cipher = SpeckCipher(0x0102030405060708, 64, 32, 'ECB')
  240. #g = cipher.encrypt(0x65736f6874206e49202e72656e6f6f70)
  241. g = cipher.encrypt(0xdeadbeefdeadbeef)
  242. print(hex(g))