blockcipher.py 25 KB

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