blockcipher.py 25 KB

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