blockcipher.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. # =============================================================================
  2. # Copyright (c) 2008 Christophe Oosterlynck <christophe.oosterlynck_AT_gmail.com>
  3. # & NXP ( Philippe Teuwen <philippe.teuwen_AT_nxp.com> )
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. # THE SOFTWARE.
  22. # =============================================================================
  23. from . import util
  24. from . import padding
  25. import collections
  26. import sys
  27. MODE_ECB = 1
  28. MODE_CBC = 2
  29. MODE_CFB = 3
  30. MODE_OFB = 5
  31. MODE_CTR = 6
  32. MODE_XTS = 7
  33. MODE_CMAC = 8
  34. class BlockCipher():
  35. """ Base class for all blockciphers
  36. """
  37. key_error_message = "Wrong key size" #should be overwritten in child classes
  38. def __init__(self,key,mode,IV,counter,cipher_module,segment_size,args={}):
  39. # Cipher classes inheriting from this one take care of:
  40. # self.blocksize
  41. # self.cipher
  42. self.key = key
  43. self.mode = mode
  44. self.cache = ''
  45. self.ed = None
  46. if 'keylen_valid' in dir(self): #wrappers for pycrypto functions don't have this function
  47. if not self.keylen_valid(key) and type(key) is not tuple:
  48. raise ValueError(self.key_error_message)
  49. if IV == None:
  50. self.IV = '\x00'*self.blocksize
  51. else:
  52. self.IV = IV
  53. if mode != MODE_XTS:
  54. self.cipher = cipher_module(self.key,**args)
  55. if mode == MODE_ECB:
  56. self.chain = ECB(self.cipher, self.blocksize)
  57. elif mode == MODE_CBC:
  58. if len(self.IV) != self.blocksize:
  59. raise Exception("the IV length should be %i bytes"%self.blocksize)
  60. self.chain = CBC(self.cipher, self.blocksize,self.IV)
  61. elif mode == MODE_CFB:
  62. if len(self.IV) != self.blocksize:
  63. raise Exception("the IV length should be %i bytes"%self.blocksize)
  64. if segment_size == None:
  65. raise ValueError("segment size must be defined explicitely for CFB mode")
  66. if segment_size > self.blocksize*8 or segment_size%8 != 0:
  67. # current CFB implementation doesn't support bit level acces => segment_size should be multiple of bytes
  68. raise ValueError("segment size should be a multiple of 8 bits between 8 and %i"%(self.blocksize*8))
  69. self.chain = CFB(self.cipher, self.blocksize,self.IV,segment_size)
  70. elif mode == MODE_OFB:
  71. if len(self.IV) != self.blocksize:
  72. raise ValueError("the IV length should be %i bytes"%self.blocksize)
  73. self.chain = OFB(self.cipher, self.blocksize,self.IV)
  74. elif mode == MODE_CTR:
  75. if (counter == None) or not isinstance(counter, collections.Callable):
  76. raise Exception("Supply a valid counter object for the CTR mode")
  77. self.chain = CTR(self.cipher,self.blocksize,counter)
  78. elif mode == MODE_XTS:
  79. if self.blocksize != 16:
  80. raise Exception('XTS only works with blockcipher that have a 128-bit blocksize')
  81. if not(type(key) == tuple and len(key) == 2):
  82. raise Exception('Supply two keys as a tuple when using XTS')
  83. if 'keylen_valid' in dir(self): #wrappers for pycrypto functions don't have this function
  84. if not self.keylen_valid(key[0]) or not self.keylen_valid(key[1]):
  85. raise ValueError(self.key_error_message)
  86. self.cipher = cipher_module(self.key[0],**args)
  87. self.cipher2 = cipher_module(self.key[1],**args)
  88. self.chain = XTS(self.cipher, self.cipher2)
  89. elif mode == MODE_CMAC:
  90. if self.blocksize not in (8,16):
  91. raise Exception('CMAC only works with blockcipher that have a 64 or 128-bit blocksize')
  92. self.chain = CMAC(self.cipher,self.blocksize,self.IV)
  93. else:
  94. raise Exception("Unknown chaining mode!")
  95. def encrypt(self,plaintext,n=''):
  96. """Encrypt some plaintext
  97. plaintext = a string of binary data
  98. n = the 'tweak' value when the chaining mode is XTS
  99. The encrypt function will encrypt the supplied plaintext.
  100. The behavior varies slightly depending on the chaining mode.
  101. ECB, CBC:
  102. ---------
  103. When the supplied plaintext is not a multiple of the blocksize
  104. of the cipher, then the remaining plaintext will be cached.
  105. The next time the encrypt function is called with some plaintext,
  106. the new plaintext will be concatenated to the cache and then
  107. cache+plaintext will be encrypted.
  108. CFB, OFB, CTR:
  109. --------------
  110. When the chaining mode allows the cipher to act as a stream cipher,
  111. the encrypt function will always encrypt all of the supplied
  112. plaintext immediately. No cache will be kept.
  113. XTS:
  114. ----
  115. Because the handling of the last two blocks is linked,
  116. it needs the whole block of plaintext to be supplied at once.
  117. Every encrypt function called on a XTS cipher will output
  118. an encrypted block based on the current supplied plaintext block.
  119. CMAC:
  120. -----
  121. Everytime the function is called, the hash from the input data is calculated.
  122. No finalizing needed.
  123. The hashlength is equal to block size of the used block cipher.
  124. """
  125. #self.ed = 'e' if chain is encrypting, 'd' if decrypting,
  126. # None if nothing happened with the chain yet
  127. #assert self.ed in ('e',None)
  128. # makes sure you don't encrypt with a cipher that has started decrypting
  129. self.ed = 'e'
  130. if self.mode == MODE_XTS:
  131. # data sequence number (or 'tweak') has to be provided when in XTS mode
  132. return self.chain.update(plaintext,'e',n)
  133. else:
  134. return self.chain.update(plaintext,'e')
  135. def decrypt(self,ciphertext,n=''):
  136. """Decrypt some ciphertext
  137. ciphertext = a string of binary data
  138. n = the 'tweak' value when the chaining mode is XTS
  139. The decrypt function will decrypt the supplied ciphertext.
  140. The behavior varies slightly depending on the chaining mode.
  141. ECB, CBC:
  142. ---------
  143. When the supplied ciphertext is not a multiple of the blocksize
  144. of the cipher, then the remaining ciphertext will be cached.
  145. The next time the decrypt function is called with some ciphertext,
  146. the new ciphertext will be concatenated to the cache and then
  147. cache+ciphertext will be decrypted.
  148. CFB, OFB, CTR:
  149. --------------
  150. When the chaining mode allows the cipher to act as a stream cipher,
  151. the decrypt function will always decrypt all of the supplied
  152. ciphertext immediately. No cache will be kept.
  153. XTS:
  154. ----
  155. Because the handling of the last two blocks is linked,
  156. it needs the whole block of ciphertext to be supplied at once.
  157. Every decrypt function called on a XTS cipher will output
  158. a decrypted block based on the current supplied ciphertext block.
  159. CMAC:
  160. -----
  161. Mode not supported for decryption as this does not make sense.
  162. """
  163. #self.ed = 'e' if chain is encrypting, 'd' if decrypting,
  164. # None if nothing happened with the chain yet
  165. #assert self.ed in ('d',None)
  166. # makes sure you don't decrypt with a cipher that has started encrypting
  167. self.ed = 'd'
  168. if self.mode == MODE_XTS:
  169. # data sequence number (or 'tweak') has to be provided when in XTS mode
  170. return self.chain.update(ciphertext,'d',n)
  171. else:
  172. return self.chain.update(ciphertext,'d')
  173. def final(self,padfct=padding.PKCS7):
  174. # TODO: after calling final, reset the IV? so the cipher is as good as new?
  175. """Finalizes the encryption by padding the cache
  176. padfct = padding function
  177. import from CryptoPlus.Util.padding
  178. For ECB, CBC: the remaining bytes in the cache will be padded and
  179. encrypted.
  180. For OFB,CFB, CTR: an encrypted padding will be returned, making the
  181. total outputed bytes since construction of the cipher
  182. a multiple of the blocksize of that cipher.
  183. If the cipher has been used for decryption, the final function won't do
  184. anything. You have to manually unpad if necessary.
  185. After finalization, the chain can still be used but the IV, counter etc
  186. aren't reset but just continue as they were after the last step (finalization step).
  187. """
  188. assert self.mode not in (MODE_XTS, MODE_CMAC) # finalizing (=padding) doesn't make sense when in XTS or CMAC mode
  189. if self.ed == 'e':
  190. # when the chain is in encryption mode, finalizing will pad the cache and encrypt this last block
  191. if self.mode in (MODE_OFB,MODE_CFB,MODE_CTR):
  192. dummy = '0'*(self.chain.totalbytes%self.blocksize) # a dummy string that will be used to get a valid padding
  193. else: #ECB, CBC
  194. dummy = self.chain.cache
  195. pad = padfct(dummy,padding.PAD,self.blocksize)[len(dummy):] # construct the padding necessary
  196. return self.chain.update(pad,'e') # supply the padding to the update function => chain cache will be "cache+padding"
  197. else:
  198. # final function doesn't make sense when decrypting => padding should be removed manually
  199. pass
  200. class ECB:
  201. """ECB chaining mode
  202. """
  203. def __init__(self, codebook, blocksize):
  204. if sys.version_info.major > 2:
  205. self.cache = b''
  206. else:
  207. self.cache = ''
  208. self.codebook = codebook
  209. self.blocksize = blocksize
  210. def update(self, data, ed):
  211. """Processes the given ciphertext/plaintext
  212. Inputs:
  213. data: raw string of any length
  214. ed: 'e' for encryption, 'd' for decryption
  215. Output:
  216. processed raw string block(s), if any
  217. When the supplied data is not a multiple of the blocksize
  218. of the cipher, then the remaining input data will be cached.
  219. The next time the update function is called with some data,
  220. the new data will be concatenated to the cache and then
  221. cache+data will be processed and full blocks will be outputted.
  222. """
  223. output_blocks = []
  224. self.cache += data
  225. if len(self.cache) < self.blocksize:
  226. return ''
  227. for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize):
  228. #the only difference between encryption/decryption in the chain is the cipher block
  229. if ed == 'e':
  230. output_blocks.append(self.codebook.encrypt( self.cache[i:i + self.blocksize] ))
  231. else:
  232. output_blocks.append(self.codebook.decrypt( self.cache[i:i + self.blocksize] ))
  233. self.cache = self.cache[i+self.blocksize:]
  234. if sys.version_info.major < 3:
  235. return ''.join(output_blocks)
  236. else:
  237. return output_blocks[0]
  238. class CBC:
  239. """CBC chaining mode
  240. """
  241. def __init__(self, codebook, blocksize, IV):
  242. self.IV = IV
  243. self.cache = ''
  244. self.codebook = codebook
  245. self.blocksize = blocksize
  246. def update(self, data, ed):
  247. """Processes the given ciphertext/plaintext
  248. Inputs:
  249. data: raw string of any length
  250. ed: 'e' for encryption, 'd' for decryption
  251. Output:
  252. processed raw string block(s), if any
  253. When the supplied data is not a multiple of the blocksize
  254. of the cipher, then the remaining input data will be cached.
  255. The next time the update function is called with some data,
  256. the new data will be concatenated to the cache and then
  257. cache+data will be processed and full blocks will be outputted.
  258. """
  259. if ed == 'e':
  260. encrypted_blocks = ''
  261. self.cache += data
  262. if len(self.cache) < self.blocksize:
  263. return ''
  264. for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize):
  265. self.IV = self.codebook.encrypt(util.xorstring(self.cache[i:i+self.blocksize],self.IV))
  266. encrypted_blocks += self.IV
  267. self.cache = self.cache[i+self.blocksize:]
  268. return encrypted_blocks
  269. else:
  270. decrypted_blocks = ''
  271. self.cache += data
  272. if len(self.cache) < self.blocksize:
  273. return ''
  274. for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize):
  275. plaintext = util.xorstring(self.IV,self.codebook.decrypt(self.cache[i:i + self.blocksize]))
  276. self.IV = self.cache[i:i + self.blocksize]
  277. decrypted_blocks+=plaintext
  278. self.cache = self.cache[i+self.blocksize:]
  279. return decrypted_blocks
  280. class CFB:
  281. # TODO: bit access instead of only byte level access
  282. """CFB Chaining Mode
  283. Can be accessed as a stream cipher.
  284. """
  285. def __init__(self, codebook, blocksize, IV,segment_size):
  286. self.codebook = codebook
  287. self.IV = IV
  288. self.blocksize = blocksize
  289. self.segment_size = segment_size/8
  290. self.keystream = []
  291. self.totalbytes = 0
  292. def update(self, data, ed):
  293. """Processes the given ciphertext/plaintext
  294. Inputs:
  295. data: raw string of any multiple of bytes
  296. ed: 'e' for encryption, 'd' for decryption
  297. Output:
  298. processed raw string
  299. The encrypt/decrypt functions will always process all of the supplied
  300. input data immediately. No cache will be kept.
  301. """
  302. output = list(data)
  303. for i in range(len(data)):
  304. if ed =='e':
  305. if len(self.keystream) == 0:
  306. block = self.codebook.encrypt(self.IV)
  307. self.keystream = list(block)[:self.segment_size] # keystream consists of the s MSB's
  308. self.IV = self.IV[self.segment_size:] # keeping (b-s) LSB's
  309. output[i] = chr(ord(output[i]) ^ ord(self.keystream.pop(0)))
  310. self.IV += output[i] # the IV for the next block in the chain is being built byte per byte as the ciphertext flows in
  311. else:
  312. if len(self.keystream) == 0:
  313. block = self.codebook.encrypt(self.IV)
  314. self.keystream = list(block)[:self.segment_size]
  315. self.IV = self.IV[self.segment_size:]
  316. self.IV += output[i]
  317. output[i] = chr(ord(output[i]) ^ ord(self.keystream.pop(0)))
  318. self.totalbytes += len(output)
  319. return ''.join(output)
  320. class OFB:
  321. """OFB Chaining Mode
  322. Can be accessed as a stream cipher.
  323. """
  324. def __init__(self, codebook, blocksize, IV):
  325. self.codebook = codebook
  326. self.IV = IV
  327. self.blocksize = blocksize
  328. self.keystream = []
  329. self.totalbytes = 0
  330. def update(self, data, ed):
  331. """Processes the given ciphertext/plaintext
  332. Inputs:
  333. data: raw string of any multiple of bytes
  334. ed: 'e' for encryption, 'd' for decryption
  335. Output:
  336. processed raw string
  337. The encrypt/decrypt functions will always process all of the supplied
  338. input data immediately. No cache will be kept.
  339. """
  340. #no difference between encryption and decryption mode
  341. n = len(data)
  342. blocksize = self.blocksize
  343. output = list(data)
  344. for i in range(n):
  345. if len(self.keystream) == 0: #encrypt a new counter block when the current keystream is fully used
  346. self.IV = self.codebook.encrypt(self.IV)
  347. self.keystream = list(self.IV)
  348. output[i] = chr(ord(output[i]) ^ ord(self.keystream.pop(0))) #as long as an encrypted counter value is available, the output is just "input XOR keystream"
  349. self.totalbytes += len(output)
  350. return ''.join(output)
  351. class CTR:
  352. """CTR Chaining Mode
  353. Can be accessed as a stream cipher.
  354. """
  355. # initial counter value can be choosen, decryption always starts from beginning
  356. # -> you can start from anywhere yourself: just feed the cipher encoded blocks and feed a counter with the corresponding value
  357. def __init__(self, codebook, blocksize, counter):
  358. self.codebook = codebook
  359. self.counter = counter
  360. self.blocksize = blocksize
  361. self.keystream = [] #holds the output of the current encrypted counter value
  362. self.totalbytes = 0
  363. def update(self, data, ed):
  364. """Processes the given ciphertext/plaintext
  365. Inputs:
  366. data: raw string of any multiple of bytes
  367. ed: 'e' for encryption, 'd' for decryption
  368. Output:
  369. processed raw string
  370. The encrypt/decrypt functions will always process all of the supplied
  371. input data immediately. No cache will be kept.
  372. """
  373. # no need for the encryption/decryption distinction: both are the same
  374. n = len(data)
  375. blocksize = self.blocksize
  376. output = list(data)
  377. for i in range(n):
  378. if len(self.keystream) == 0: #encrypt a new counter block when the current keystream is fully used
  379. block = self.codebook.encrypt(self.counter())
  380. self.keystream = list(block)
  381. output[i] = chr(ord(output[i])^ord(self.keystream.pop(0))) #as long as an encrypted counter value is available, the output is just "input XOR keystream"
  382. self.totalbytes += len(output)
  383. return ''.join(output)
  384. class XTS:
  385. """XTS Chaining Mode
  386. Usable with blockciphers with a 16-byte blocksize
  387. """
  388. # TODO: allow other blocksizes besides 16bytes?
  389. def __init__(self,codebook1, codebook2):
  390. self.cache = ''
  391. self.codebook1 = codebook1
  392. self.codebook2 = codebook2
  393. def update(self, data, ed,tweak=''):
  394. # supply n as a raw string
  395. # tweak = data sequence number
  396. """Perform a XTS encrypt/decrypt operation.
  397. Because the handling of the last two blocks is linked,
  398. it needs the whole block of ciphertext to be supplied at once.
  399. Every decrypt function called on a XTS cipher will output
  400. a decrypted block based on the current supplied ciphertext block.
  401. """
  402. output = ''
  403. assert len(data) > 15, "At least one block of 128 bits needs to be supplied"
  404. assert len(data) < 128*pow(2,20)
  405. # initializing T
  406. # e_k2_n = E_K2(tweak)
  407. e_k2_n = self.codebook2.encrypt(tweak+ '\x00' * (16-len(tweak)))[::-1]
  408. self.T = util.string2number(e_k2_n)
  409. i=0
  410. while i < ((len(data) // 16)-1): #Decrypt all the blocks but one last full block and opt one last partial block
  411. # C = E_K1(P xor T) xor T
  412. output += self.__xts_step(ed,data[i*16:(i+1)*16],self.T)
  413. # T = E_K2(n) mul (a pow i)
  414. self.__T_update()
  415. i+=1
  416. # Check if the data supplied is a multiple of 16 bytes -> one last full block and we're done
  417. if len(data[i*16:]) == 16:
  418. # C = E_K1(P xor T) xor T
  419. output += self.__xts_step(ed,data[i*16:(i+1)*16],self.T)
  420. # T = E_K2(n) mul (a pow i)
  421. self.__T_update()
  422. else:
  423. T_temp = [self.T]
  424. self.__T_update()
  425. T_temp.append(self.T)
  426. if ed=='d':
  427. # Permutation of the last two indexes
  428. T_temp.reverse()
  429. # Decrypt/Encrypt the last two blocks when data is not a multiple of 16 bytes
  430. Cm1 = data[i*16:(i+1)*16]
  431. Cm = data[(i+1)*16:]
  432. PP = self.__xts_step(ed,Cm1,T_temp[0])
  433. Cp = PP[len(Cm):]
  434. Pm = PP[:len(Cm)]
  435. CC = Cm+Cp
  436. Pm1 = self.__xts_step(ed,CC,T_temp[1])
  437. output += Pm1 + Pm
  438. return output
  439. def __xts_step(self,ed,tocrypt,T):
  440. T_string = util.number2string_N(T,16)[::-1]
  441. # C = E_K1(P xor T) xor T
  442. if ed == 'd':
  443. return util.xorstring(T_string, self.codebook1.decrypt(util.xorstring(T_string, tocrypt)))
  444. else:
  445. return util.xorstring(T_string, self.codebook1.encrypt(util.xorstring(T_string, tocrypt)))
  446. def __T_update(self):
  447. # Used for calculating T for a certain step using the T value from the previous step
  448. self.T = self.T << 1
  449. # if (Cout)
  450. if self.T >> (8*16):
  451. #T[0] ^= GF_128_FDBK;
  452. self.T = self.T ^ 0x100000000000000000000000000000087
  453. class CMAC:
  454. """CMAC chaining mode
  455. Supports every cipher with a blocksize available
  456. in the list CMAC.supported_blocksizes.
  457. The hashlength is equal to block size of the used block cipher.
  458. Usable with blockciphers with a 8 or 16-byte blocksize
  459. """
  460. # TODO: move to hash module?
  461. # TODO: change update behaviour to .update() and .digest() as for all hash modules?
  462. # -> other hash functions in pycrypto: calling update, concatenates current input with previous input and hashes everything
  463. __Rb_dictionary = {64:0x000000000000001b,128:0x00000000000000000000000000000087}
  464. supported_blocksizes = list(__Rb_dictionary.keys())
  465. def __init__(self,codebook,blocksize,IV):
  466. # Purpose of init: calculate Lu & Lu2
  467. #blocksize (in bytes): to select the Rb constant in the dictionary
  468. #Rb as a dictionary: adding support for other blocksizes is easy
  469. self.cache=''
  470. self.blocksize = blocksize
  471. self.codebook = codebook
  472. self.IV = IV
  473. #Rb_dictionary: holds values for Rb for different blocksizes
  474. # values for 64 and 128 bits found here: http://www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
  475. # explanation from: http://csrc.nist.gov/publications/nistpubs/800-38B/SP_800-38B.pdf
  476. # Rb is a representation of a certain irreducible binary polynomial of degree b, namely,
  477. # the lexicographically first among all such polynomials with the minimum possible number of
  478. # nonzero terms. If this polynomial is expressed as ub+cb-1ub-1+...+c2u2+c1u+c0, where the
  479. # coefficients cb-1, cb-2, ..., c2, c1, c0 are either 0 or 1, then Rb is the bit string cb-1cb-2...c2c1c0.
  480. self.Rb = self.__Rb_dictionary[blocksize*8]
  481. mask1 = int(('\xff'*blocksize).encode('hex'),16)
  482. mask2 = int(('\x80' + '\x00'*(blocksize-1) ).encode('hex'),16)
  483. L = int(self.codebook.encrypt('\x00'*blocksize).encode('hex'),16)
  484. if L & mask2:
  485. Lu = ((L << 1) & mask1) ^ self.Rb
  486. else:
  487. Lu = L << 1
  488. Lu = Lu & mask1
  489. if Lu & mask2:
  490. Lu2 = ((Lu << 1) & mask1)^ self.Rb
  491. else:
  492. Lu2 = Lu << 1
  493. Lu2 = Lu2 & mask1
  494. self.Lu =util.number2string_N(Lu,self.blocksize)
  495. self.Lu2=util.number2string_N(Lu2,self.blocksize)
  496. def update(self, data, ed):
  497. """Processes the given ciphertext/plaintext
  498. Inputs:
  499. data: raw string of any length
  500. ed: 'e' for encryption, 'd' for decryption
  501. Output:
  502. hashed data as raw string
  503. This is not really an update function:
  504. Everytime the function is called, the hash from the input data is calculated.
  505. No finalizing needed.
  506. """
  507. assert ed == 'e'
  508. blocksize = self.blocksize
  509. m = (len(data)+blocksize-1)/blocksize #m = amount of datablocks
  510. i=0
  511. for i in range(1,m):
  512. self.IV = self.codebook.encrypt( util.xorstring(data[(i-1)*blocksize:(i)*blocksize],self.IV) )
  513. if len(data[(i)*blocksize:])==blocksize:
  514. X = util.xorstring(util.xorstring(data[(i)*blocksize:],self.IV),self.Lu)
  515. else:
  516. tmp = data[(i)*blocksize:] + '\x80' + '\x00'*(blocksize - len(data[(i)*blocksize:])-1)
  517. X = util.xorstring(util.xorstring(tmp,self.IV),self.Lu2)
  518. T = self.codebook.encrypt(X)
  519. return T