/gdata/Crypto/Protocol/AllOrNothing.py

http://radioappz.googlecode.com/ · Python · 295 lines · 199 code · 14 blank · 82 comment · 2 complexity · ebf36f21ca3aa5eaf26da519be83bdac MD5 · raw file

  1. """This file implements all-or-nothing package transformations.
  2. An all-or-nothing package transformation is one in which some text is
  3. transformed into message blocks, such that all blocks must be obtained before
  4. the reverse transformation can be applied. Thus, if any blocks are corrupted
  5. or lost, the original message cannot be reproduced.
  6. An all-or-nothing package transformation is not encryption, although a block
  7. cipher algorithm is used. The encryption key is randomly generated and is
  8. extractable from the message blocks.
  9. This class implements the All-Or-Nothing package transformation algorithm
  10. described in:
  11. Ronald L. Rivest. "All-Or-Nothing Encryption and The Package Transform"
  12. http://theory.lcs.mit.edu/~rivest/fusion.pdf
  13. """
  14. __revision__ = "$Id: AllOrNothing.py,v 1.8 2003/02/28 15:23:20 akuchling Exp $"
  15. import operator
  16. import string
  17. from Crypto.Util.number import bytes_to_long, long_to_bytes
  18. class AllOrNothing:
  19. """Class implementing the All-or-Nothing package transform.
  20. Methods for subclassing:
  21. _inventkey(key_size):
  22. Returns a randomly generated key. Subclasses can use this to
  23. implement better random key generating algorithms. The default
  24. algorithm is probably not very cryptographically secure.
  25. """
  26. def __init__(self, ciphermodule, mode=None, IV=None):
  27. """AllOrNothing(ciphermodule, mode=None, IV=None)
  28. ciphermodule is a module implementing the cipher algorithm to
  29. use. It must provide the PEP272 interface.
  30. Note that the encryption key is randomly generated
  31. automatically when needed. Optional arguments mode and IV are
  32. passed directly through to the ciphermodule.new() method; they
  33. are the feedback mode and initialization vector to use. All
  34. three arguments must be the same for the object used to create
  35. the digest, and to undigest'ify the message blocks.
  36. """
  37. self.__ciphermodule = ciphermodule
  38. self.__mode = mode
  39. self.__IV = IV
  40. self.__key_size = ciphermodule.key_size
  41. if self.__key_size == 0:
  42. self.__key_size = 16
  43. __K0digit = chr(0x69)
  44. def digest(self, text):
  45. """digest(text:string) : [string]
  46. Perform the All-or-Nothing package transform on the given
  47. string. Output is a list of message blocks describing the
  48. transformed text, where each block is a string of bit length equal
  49. to the ciphermodule's block_size.
  50. """
  51. # generate a random session key and K0, the key used to encrypt the
  52. # hash blocks. Rivest calls this a fixed, publically-known encryption
  53. # key, but says nothing about the security implications of this key or
  54. # how to choose it.
  55. key = self._inventkey(self.__key_size)
  56. K0 = self.__K0digit * self.__key_size
  57. # we need two cipher objects here, one that is used to encrypt the
  58. # message blocks and one that is used to encrypt the hashes. The
  59. # former uses the randomly generated key, while the latter uses the
  60. # well-known key.
  61. mcipher = self.__newcipher(key)
  62. hcipher = self.__newcipher(K0)
  63. # Pad the text so that its length is a multiple of the cipher's
  64. # block_size. Pad with trailing spaces, which will be eliminated in
  65. # the undigest() step.
  66. block_size = self.__ciphermodule.block_size
  67. padbytes = block_size - (len(text) % block_size)
  68. text = text + ' ' * padbytes
  69. # Run through the algorithm:
  70. # s: number of message blocks (size of text / block_size)
  71. # input sequence: m1, m2, ... ms
  72. # random key K' (`key' in the code)
  73. # Compute output sequence: m'1, m'2, ... m's' for s' = s + 1
  74. # Let m'i = mi ^ E(K', i) for i = 1, 2, 3, ..., s
  75. # Let m's' = K' ^ h1 ^ h2 ^ ... hs
  76. # where hi = E(K0, m'i ^ i) for i = 1, 2, ... s
  77. #
  78. # The one complication I add is that the last message block is hard
  79. # coded to the number of padbytes added, so that these can be stripped
  80. # during the undigest() step
  81. s = len(text) / block_size
  82. blocks = []
  83. hashes = []
  84. for i in range(1, s+1):
  85. start = (i-1) * block_size
  86. end = start + block_size
  87. mi = text[start:end]
  88. assert len(mi) == block_size
  89. cipherblock = mcipher.encrypt(long_to_bytes(i, block_size))
  90. mticki = bytes_to_long(mi) ^ bytes_to_long(cipherblock)
  91. blocks.append(mticki)
  92. # calculate the hash block for this block
  93. hi = hcipher.encrypt(long_to_bytes(mticki ^ i, block_size))
  94. hashes.append(bytes_to_long(hi))
  95. # Add the padbytes length as a message block
  96. i = i + 1
  97. cipherblock = mcipher.encrypt(long_to_bytes(i, block_size))
  98. mticki = padbytes ^ bytes_to_long(cipherblock)
  99. blocks.append(mticki)
  100. # calculate this block's hash
  101. hi = hcipher.encrypt(long_to_bytes(mticki ^ i, block_size))
  102. hashes.append(bytes_to_long(hi))
  103. # Now calculate the last message block of the sequence 1..s'. This
  104. # will contain the random session key XOR'd with all the hash blocks,
  105. # so that for undigest(), once all the hash blocks are calculated, the
  106. # session key can be trivially extracted. Calculating all the hash
  107. # blocks requires that all the message blocks be received, thus the
  108. # All-or-Nothing algorithm succeeds.
  109. mtick_stick = bytes_to_long(key) ^ reduce(operator.xor, hashes)
  110. blocks.append(mtick_stick)
  111. # we convert the blocks to strings since in Python, byte sequences are
  112. # always represented as strings. This is more consistent with the
  113. # model that encryption and hash algorithms always operate on strings.
  114. return map(long_to_bytes, blocks)
  115. def undigest(self, blocks):
  116. """undigest(blocks : [string]) : string
  117. Perform the reverse package transformation on a list of message
  118. blocks. Note that the ciphermodule used for both transformations
  119. must be the same. blocks is a list of strings of bit length
  120. equal to the ciphermodule's block_size.
  121. """
  122. # better have at least 2 blocks, for the padbytes package and the hash
  123. # block accumulator
  124. if len(blocks) < 2:
  125. raise ValueError, "List must be at least length 2."
  126. # blocks is a list of strings. We need to deal with them as long
  127. # integers
  128. blocks = map(bytes_to_long, blocks)
  129. # Calculate the well-known key, to which the hash blocks are
  130. # encrypted, and create the hash cipher.
  131. K0 = self.__K0digit * self.__key_size
  132. hcipher = self.__newcipher(K0)
  133. # Since we have all the blocks (or this method would have been called
  134. # prematurely), we can calcualte all the hash blocks.
  135. hashes = []
  136. for i in range(1, len(blocks)):
  137. mticki = blocks[i-1] ^ i
  138. hi = hcipher.encrypt(long_to_bytes(mticki))
  139. hashes.append(bytes_to_long(hi))
  140. # now we can calculate K' (key). remember the last block contains
  141. # m's' which we don't include here
  142. key = blocks[-1] ^ reduce(operator.xor, hashes)
  143. # and now we can create the cipher object
  144. mcipher = self.__newcipher(long_to_bytes(key))
  145. block_size = self.__ciphermodule.block_size
  146. # And we can now decode the original message blocks
  147. parts = []
  148. for i in range(1, len(blocks)):
  149. cipherblock = mcipher.encrypt(long_to_bytes(i, block_size))
  150. mi = blocks[i-1] ^ bytes_to_long(cipherblock)
  151. parts.append(mi)
  152. # The last message block contains the number of pad bytes appended to
  153. # the original text string, such that its length was an even multiple
  154. # of the cipher's block_size. This number should be small enough that
  155. # the conversion from long integer to integer should never overflow
  156. padbytes = int(parts[-1])
  157. text = string.join(map(long_to_bytes, parts[:-1]), '')
  158. return text[:-padbytes]
  159. def _inventkey(self, key_size):
  160. # TBD: Not a very secure algorithm. Eventually, I'd like to use JHy's
  161. # kernelrand module
  162. import time
  163. from Crypto.Util import randpool
  164. # TBD: key_size * 2 to work around possible bug in RandomPool?
  165. pool = randpool.RandomPool(key_size * 2)
  166. while key_size > pool.entropy:
  167. pool.add_event()
  168. # we now have enough entropy in the pool to get a key_size'd key
  169. return pool.get_bytes(key_size)
  170. def __newcipher(self, key):
  171. if self.__mode is None and self.__IV is None:
  172. return self.__ciphermodule.new(key)
  173. elif self.__IV is None:
  174. return self.__ciphermodule.new(key, self.__mode)
  175. else:
  176. return self.__ciphermodule.new(key, self.__mode, self.__IV)
  177. if __name__ == '__main__':
  178. import sys
  179. import getopt
  180. import base64
  181. usagemsg = '''\
  182. Test module usage: %(program)s [-c cipher] [-l] [-h]
  183. Where:
  184. --cipher module
  185. -c module
  186. Cipher module to use. Default: %(ciphermodule)s
  187. --aslong
  188. -l
  189. Print the encoded message blocks as long integers instead of base64
  190. encoded strings
  191. --help
  192. -h
  193. Print this help message
  194. '''
  195. ciphermodule = 'AES'
  196. aslong = 0
  197. def usage(code, msg=None):
  198. if msg:
  199. print msg
  200. print usagemsg % {'program': sys.argv[0],
  201. 'ciphermodule': ciphermodule}
  202. sys.exit(code)
  203. try:
  204. opts, args = getopt.getopt(sys.argv[1:],
  205. 'c:l', ['cipher=', 'aslong'])
  206. except getopt.error, msg:
  207. usage(1, msg)
  208. if args:
  209. usage(1, 'Too many arguments')
  210. for opt, arg in opts:
  211. if opt in ('-h', '--help'):
  212. usage(0)
  213. elif opt in ('-c', '--cipher'):
  214. ciphermodule = arg
  215. elif opt in ('-l', '--aslong'):
  216. aslong = 1
  217. # ugly hack to force __import__ to give us the end-path module
  218. module = __import__('Crypto.Cipher.'+ciphermodule, None, None, ['new'])
  219. a = AllOrNothing(module)
  220. print 'Original text:\n=========='
  221. print __doc__
  222. print '=========='
  223. msgblocks = a.digest(__doc__)
  224. print 'message blocks:'
  225. for i, blk in map(None, range(len(msgblocks)), msgblocks):
  226. # base64 adds a trailing newline
  227. print ' %3d' % i,
  228. if aslong:
  229. print bytes_to_long(blk)
  230. else:
  231. print base64.encodestring(blk)[:-1]
  232. #
  233. # get a new undigest-only object so there's no leakage
  234. b = AllOrNothing(module)
  235. text = b.undigest(msgblocks)
  236. if text == __doc__:
  237. print 'They match!'
  238. else:
  239. print 'They differ!'