fork(29) download
  1. #############################################################################
  2. # Documentation #
  3. #############################################################################
  4. # Author: Todd Whiteman
  5. # Date: 7th May, 2003
  6. # Verion: 1.1
  7. # Homepage: http://h...content-available-to-author-only...t.au/~twhitema/des.html
  8. #
  9. # Modifications to 3des CBC code by Matt Johnston 2004 <matt at ucc asn au>
  10. #
  11. # This algorithm is a pure python implementation of the DES algorithm.
  12. # It is in pure python to avoid portability issues, since most DES
  13. # implementations are programmed in C (for performance reasons).
  14. #
  15. # Triple DES class is also implemented, utilising the DES base. Triple DES
  16. # is either DES-EDE3 with a 24 byte key, or DES-EDE2 with a 16 byte key.
  17. #
  18. # See the README.txt that should come with this python module for the
  19. # implementation methods used.
  20. """A pure python implementation of the DES and TRIPLE DES encryption algorithms
  21. pyDes.des(key, [mode], [IV])
  22. pyDes.triple_des(key, [mode], [IV])
  23. key -> String containing the encryption key. 8 bytes for DES, 16 or 24 bytes
  24. for Triple DES
  25. mode -> Optional argument for encryption type, can be either
  26. pyDes.ECB (Electronic Code Book) or pyDes.CBC (Cypher Block Chaining)
  27. IV -> Optional argument, must be supplied if using CBC mode. Must be 8 bytes
  28. Example:
  29. from pyDes import *
  30. data = "Please encrypt my string"
  31. k = des("DESCRYPT", " ", CBC, "\0\0\0\0\0\0\0\0")
  32. d = k.encrypt(data)
  33. print "Encypted string: " + d
  34. print "Decypted string: " + k.decrypt(d)
  35. See the module source (pyDes.py) for more examples of use.
  36. You can slo run the pyDes.py file without and arguments to see a simple test.
  37. Note: This code was not written for high-end systems needing a fast
  38. implementation, but rather a handy portable solution with small usage.
  39. """
  40. # Modes of crypting / cyphering
  41. ECB = 0
  42. CBC = 1
  43. #############################################################################
  44. # DES #
  45. #############################################################################
  46. class des:
  47. """DES encryption/decrytpion class
  48. Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes.
  49. pyDes.des(key,[mode], [IV])
  50. key -> The encryption key string, must be exactly 8 bytes
  51. mode -> Optional argument for encryption type, can be either pyDes.ECB
  52. (Electronic Code Book), pyDes.CBC (Cypher Block Chaining)
  53. IV -> Optional string argument, must be supplied if using CBC mode.
  54. Must be 8 bytes in length.
  55. """
  56. # Permutation and translation tables for DES
  57. __pc1 = [56, 48, 40, 32, 24, 16, 8,
  58. 0, 57, 49, 41, 33, 25, 17,
  59. 9, 1, 58, 50, 42, 34, 26,
  60. 18, 10, 2, 59, 51, 43, 35,
  61. 62, 54, 46, 38, 30, 22, 14,
  62. 6, 61, 53, 45, 37, 29, 21,
  63. 13, 5, 60, 52, 44, 36, 28,
  64. 20, 12, 4, 27, 19, 11, 3
  65. ]
  66. # number left rotations of pc1
  67. __left_rotations = [
  68. 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
  69. ]
  70. # permuted choice key (table 2)
  71. __pc2 = [
  72. 13, 16, 10, 23, 0, 4,
  73. 2, 27, 14, 5, 20, 9,
  74. 22, 18, 11, 3, 25, 7,
  75. 15, 6, 26, 19, 12, 1,
  76. 40, 51, 30, 36, 46, 54,
  77. 29, 39, 50, 44, 32, 47,
  78. 43, 48, 38, 55, 33, 52,
  79. 45, 41, 49, 35, 28, 31
  80. ]
  81. # initial permutation IP
  82. __ip = [57, 49, 41, 33, 25, 17, 9, 1,
  83. 59, 51, 43, 35, 27, 19, 11, 3,
  84. 61, 53, 45, 37, 29, 21, 13, 5,
  85. 63, 55, 47, 39, 31, 23, 15, 7,
  86. 56, 48, 40, 32, 24, 16, 8, 0,
  87. 58, 50, 42, 34, 26, 18, 10, 2,
  88. 60, 52, 44, 36, 28, 20, 12, 4,
  89. 62, 54, 46, 38, 30, 22, 14, 6
  90. ]
  91. # Expansion table for turning 32 bit blocks into 48 bits
  92. __expansion_table = [
  93. 31, 0, 1, 2, 3, 4,
  94. 3, 4, 5, 6, 7, 8,
  95. 7, 8, 9, 10, 11, 12,
  96. 11, 12, 13, 14, 15, 16,
  97. 15, 16, 17, 18, 19, 20,
  98. 19, 20, 21, 22, 23, 24,
  99. 23, 24, 25, 26, 27, 28,
  100. 27, 28, 29, 30, 31, 0
  101. ]
  102. # The (in)famous S-boxes
  103. __sbox = [
  104. # S1
  105. [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
  106. 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
  107. 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
  108. 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
  109. # S2
  110. [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
  111. 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
  112. 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
  113. 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
  114. # S3
  115. [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
  116. 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
  117. 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
  118. 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
  119. # S4
  120. [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
  121. 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
  122. 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
  123. 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
  124. # S5
  125. [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
  126. 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
  127. 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
  128. 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
  129. # S6
  130. [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
  131. 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
  132. 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
  133. 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
  134. # S7
  135. [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
  136. 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
  137. 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
  138. 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
  139. # S8
  140. [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
  141. 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
  142. 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
  143. 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
  144. ]
  145. # 32-bit permutation function P used on the output of the S-boxes
  146. __p = [
  147. 15, 6, 19, 20, 28, 11,
  148. 27, 16, 0, 14, 22, 25,
  149. 4, 17, 30, 9, 1, 7,
  150. 23,13, 31, 26, 2, 8,
  151. 18, 12, 29, 5, 21, 10,
  152. 3, 24
  153. ]
  154. # final permutation IP^-1
  155. __fp = [
  156. 39, 7, 47, 15, 55, 23, 63, 31,
  157. 38, 6, 46, 14, 54, 22, 62, 30,
  158. 37, 5, 45, 13, 53, 21, 61, 29,
  159. 36, 4, 44, 12, 52, 20, 60, 28,
  160. 35, 3, 43, 11, 51, 19, 59, 27,
  161. 34, 2, 42, 10, 50, 18, 58, 26,
  162. 33, 1, 41, 9, 49, 17, 57, 25,
  163. 32, 0, 40, 8, 48, 16, 56, 24
  164. ]
  165. # Type of crypting being done
  166. ENCRYPT = 0x00
  167. DECRYPT = 0x01
  168. # Initialisation
  169. def __init__(self, key, mode=ECB, IV=None):
  170. if len(key) != 8:
  171. raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.")
  172. self.block_size = 8
  173. self.key_size = 8
  174. self.__padding = ''
  175. # Set the passed in variables
  176. self.setMode(mode)
  177. if IV:
  178. self.setIV(IV)
  179. self.L = []
  180. self.R = []
  181. self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16)
  182. self.final = []
  183. self.setKey(key)
  184. def getKey(self):
  185. """getKey() -> string"""
  186. return self.__key
  187. def setKey(self, key):
  188. """Will set the crypting key for this object. Must be 8 bytes."""
  189. self.__key = key
  190. self.__create_sub_keys()
  191. def getMode(self):
  192. """getMode() -> pyDes.ECB or pyDes.CBC"""
  193. return self.__mode
  194. def setMode(self, mode):
  195. """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC"""
  196. self.__mode = mode
  197. def getIV(self):
  198. """getIV() -> string"""
  199. return self.__iv
  200. def setIV(self, IV):
  201. """Will set the Initial Value, used in conjunction with CBC mode"""
  202. if not IV or len(IV) != self.block_size:
  203. raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes")
  204. self.__iv = IV
  205. def getPadding(self):
  206. """getPadding() -> string of length 1. Padding character."""
  207. return self.__padding
  208. def __String_to_BitList(self, data):
  209. """Turn the string data, into a list of bits (1, 0)'s"""
  210. l = len(data) * 8
  211. result = [0] * l
  212. pos = 0
  213. for c in data:
  214. i = 7
  215. ch = ord(c)
  216. while i >= 0:
  217. if ch & (1 << i) != 0:
  218. result[pos] = 1
  219. else:
  220. result[pos] = 0
  221. pos += 1
  222. i -= 1
  223. return result
  224. def __BitList_to_String(self, data):
  225. """Turn the list of bits -> data, into a string"""
  226. result = ''
  227. pos = 0
  228. c = 0
  229. while pos < len(data):
  230. c += data[pos] << (7 - (pos % 8))
  231. if (pos % 8) == 7:
  232. result += chr(c)
  233. c = 0
  234. pos += 1
  235. return result
  236. def __permutate(self, table, block):
  237. """Permutate this block with the specified table"""
  238. return map(lambda x: block[x], table)
  239. # Transform the secret key, so that it is ready for data processing
  240. # Create the 16 subkeys, K[1] - K[16]
  241. def __create_sub_keys(self):
  242. """Create the 16 subkeys K[1] to K[16] from the given key"""
  243. key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey()))
  244. i = 0
  245. # Split into Left and Right sections
  246. self.L = key[:28]
  247. self.R = key[28:]
  248. while i < 16:
  249. j = 0
  250. # Perform circular left shifts
  251. while j < des.__left_rotations[i]:
  252. self.L.append(self.L[0])
  253. del self.L[0]
  254. self.R.append(self.R[0])
  255. del self.R[0]
  256. j += 1
  257. # Create one of the 16 subkeys through pc2 permutation
  258. self.Kn[i] = self.__permutate(des.__pc2, self.L + self.R)
  259. i += 1
  260. # Main part of the encryption algorithm, the number cruncher :)
  261. def __des_crypt(self, block, crypt_type):
  262. """Crypt the block of data through DES bit-manipulation"""
  263. block = self.__permutate(des.__ip, block)
  264. self.L = block[:32]
  265. self.R = block[32:]
  266. # Encryption starts from Kn[1] through to Kn[16]
  267. if crypt_type == des.ENCRYPT:
  268. iteration = 0
  269. iteration_adjustment = 1
  270. # Decryption starts from Kn[16] down to Kn[1]
  271. else:
  272. iteration = 15
  273. iteration_adjustment = -1
  274. i = 0
  275. while i < 16:
  276. # Make a copy of R[i-1], this will later become L[i]
  277. tempR = self.R[:]
  278. # Permutate R[i - 1] to start creating R[i]
  279. self.R = self.__permutate(des.__expansion_table, self.R)
  280. # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here
  281. self.R = map(lambda x, y: x ^ y, self.R, self.Kn[iteration])
  282. B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]]
  283. # Optimization: Replaced below commented code with above
  284. #j = 0
  285. #B = []
  286. #while j < len(self.R):
  287. # self.R[j] = self.R[j] ^ self.Kn[iteration][j]
  288. # j += 1
  289. # if j % 6 == 0:
  290. # B.append(self.R[j-6:j])
  291. # Permutate B[1] to B[8] using the S-Boxes
  292. j = 0
  293. Bn = [0] * 32
  294. pos = 0
  295. while j < 8:
  296. # Work out the offsets
  297. m = (B[j][0] << 1) + B[j][5]
  298. n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4]
  299. # Find the permutation value
  300. v = des.__sbox[j][(m << 4) + n]
  301. # Turn value into bits, add it to result: Bn
  302. Bn[pos] = (v & 8) >> 3
  303. Bn[pos + 1] = (v & 4) >> 2
  304. Bn[pos + 2] = (v & 2) >> 1
  305. Bn[pos + 3] = v & 1
  306. pos += 4
  307. j += 1
  308. # Permutate the concatination of B[1] to B[8] (Bn)
  309. self.R = self.__permutate(des.__p, Bn)
  310. # Xor with L[i - 1]
  311. self.R = map(lambda x, y: x ^ y, self.R, self.L)
  312. # Optimization: This now replaces the below commented code
  313. #j = 0
  314. #while j < len(self.R):
  315. # self.R[j] = self.R[j] ^ self.L[j]
  316. # j += 1
  317. # L[i] becomes R[i - 1]
  318. self.L = tempR
  319. i += 1
  320. iteration += iteration_adjustment
  321. # Final permutation of R[16]L[16]
  322. self.final = self.__permutate(des.__fp, self.R + self.L)
  323. return self.final
  324. # Data to be encrypted/decrypted
  325. def crypt(self, data, crypt_type):
  326. """Crypt the data in blocks, running it through des_crypt()"""
  327. # Error check the data
  328. if not data:
  329. return ''
  330. if len(data) % self.block_size != 0:
  331. if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks
  332. raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.")
  333. if not self.getPadding():
  334. raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character")
  335. else:
  336. data += (self.block_size - (len(data) % self.block_size)) * self.getPadding()
  337. # print "Len of data: %f" % (len(data) / self.block_size)
  338. if self.getMode() == CBC:
  339. if self.getIV():
  340. iv = self.__String_to_BitList(self.getIV())
  341. else:
  342. raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering")
  343. # Split the data into blocks, crypting each one seperately
  344. i = 0
  345. dict = {}
  346. result = []
  347. #cached = 0
  348. #lines = 0
  349. while i < len(data):
  350. # Test code for caching encryption results
  351. #lines += 1
  352. #if dict.has_key(data[i:i+8]):
  353. #print "Cached result for: %s" % data[i:i+8]
  354. # cached += 1
  355. # result.append(dict[data[i:i+8]])
  356. # i += 8
  357. # continue
  358. block = self.__String_to_BitList(data[i:i+8])
  359. # Xor with IV if using CBC mode
  360. if self.getMode() == CBC:
  361. if crypt_type == des.ENCRYPT:
  362. block = map(lambda x, y: x ^ y, block, iv)
  363. #j = 0
  364. #while j < len(block):
  365. # block[j] = block[j] ^ iv[j]
  366. # j += 1
  367. processed_block = self.__des_crypt(block, crypt_type)
  368. if crypt_type == des.DECRYPT:
  369. processed_block = map(lambda x, y: x ^ y, processed_block, iv)
  370. #j = 0
  371. #while j < len(processed_block):
  372. # processed_block[j] = processed_block[j] ^ iv[j]
  373. # j += 1
  374. iv = block
  375. else:
  376. iv = processed_block
  377. else:
  378. processed_block = self.__des_crypt(block, crypt_type)
  379. # Add the resulting crypted block to our list
  380. #d = self.__BitList_to_String(processed_block)
  381. #result.append(d)
  382. result.append(self.__BitList_to_String(processed_block))
  383. #dict[data[i:i+8]] = d
  384. i += 8
  385. # print "Lines: %d, cached: %d" % (lines, cached)
  386. # Remove the padding from the last block
  387. if crypt_type == des.DECRYPT and self.getPadding():
  388. #print "Removing decrypt pad"
  389. s = result[-1]
  390. while s[-1] == self.getPadding():
  391. s = s[:-1]
  392. result[-1] = s
  393. # Return the full crypted string
  394. return ''.join(result)
  395. def encrypt(self, data, pad=''):
  396. """encrypt(data, [pad]) -> string
  397. data : String to be encrypted
  398. pad : Optional argument for encryption padding. Must only be one byte
  399. The data must be a multiple of 8 bytes and will be encrypted
  400. with the already specified key. Data does not have to be a
  401. multiple of 8 bytes if the padding character is supplied, the
  402. data will then be padded to a multiple of 8 bytes with this
  403. pad character.
  404. """
  405. self.__padding = pad
  406. return self.crypt(data, des.ENCRYPT)
  407. def decrypt(self, data, pad=''):
  408. """decrypt(data, [pad]) -> string
  409. data : String to be encrypted
  410. pad : Optional argument for decryption padding. Must only be one byte
  411. The data must be a multiple of 8 bytes and will be decrypted
  412. with the already specified key. If the optional padding character
  413. is supplied, then the un-encypted data will have the padding characters
  414. removed from the end of the string. This pad removal only occurs on the
  415. last 8 bytes of the data (last data block).
  416. """
  417. self.__padding = pad
  418. return self.crypt(data, des.DECRYPT)
  419. #############################################################################
  420. # Triple DES #
  421. #############################################################################
  422. class triple_des:
  423. """Triple DES encryption/decrytpion class
  424. This algorithm uses the DES-EDE3 (when a 24 byte key is supplied) or
  425. the DES-EDE2 (when a 16 byte key is supplied) encryption methods.
  426. Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes.
  427. pyDes.des(key, [mode], [IV])
  428. key -> The encryption key string, must be either 16 or 24 bytes long
  429. mode -> Optional argument for encryption type, can be either pyDes.ECB
  430. (Electronic Code Book), pyDes.CBC (Cypher Block Chaining)
  431. IV -> Optional string argument, must be supplied if using CBC mode.
  432. Must be 8 bytes in length.
  433. """
  434. def __init__(self, key, mode=ECB, IV=None):
  435. self.block_size = 8
  436. self.setMode(mode)
  437. self.__padding = ''
  438. self.__iv = IV
  439. self.setKey(key)
  440. def getKey(self):
  441. """getKey() -> string"""
  442. return self.__key
  443. def setKey(self, key):
  444. """Will set the crypting key for this object. Either 16 or 24 bytes long."""
  445. self.key_size = 24 # Use DES-EDE3 mode
  446. if len(key) != self.key_size:
  447. if len(key) == 16: # Use DES-EDE2 mode
  448. self.key_size = 16
  449. else:
  450. raise ValueError("Invalid triple DES key size. Key must be either 16 or 24 bytes long")
  451. if self.getMode() == CBC and (not self.getIV() or len(self.getIV()) != self.block_size):
  452. raise ValueError("Invalid IV, must be 8 bytes in length") ## TODO: Check this
  453. # modes get handled later, since CBC goes on top of the triple-des
  454. self.__key1 = des(key[:8])
  455. self.__key2 = des(key[8:16])
  456. if self.key_size == 16:
  457. self.__key3 = self.__key1
  458. else:
  459. self.__key3 = des(key[16:])
  460. self.__key = key
  461. def getMode(self):
  462. """getMode() -> pyDes.ECB or pyDes.CBC"""
  463. return self.__mode
  464. def setMode(self, mode):
  465. """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC"""
  466. self.__mode = mode
  467. def getIV(self):
  468. """getIV() -> string"""
  469. return self.__iv
  470. def setIV(self, IV):
  471. """Will set the Initial Value, used in conjunction with CBC mode"""
  472. self.__iv = IV
  473. def xorstr( self, x, y ):
  474. """Returns the bitwise xor of the bytes in two strings"""
  475. if len(x) != len(y):
  476. raise "string lengths differ %d %d" % (len(x), len(y))
  477. ret = ''
  478. for i in range(len(x)):
  479. ret += chr(ord(x[i]) ^ ord(y[i]))
  480. return ret
  481. def encrypt(self, data, pad=''):
  482. """encrypt(data, [pad]) -> string
  483. data : String to be encrypted
  484. pad : Optional argument for encryption padding. Must only be one byte
  485. The data must be a multiple of 8 bytes and will be encrypted
  486. with the already specified key. Data does not have to be a
  487. multiple of 8 bytes if the padding character is supplied, the
  488. data will then be padded to a multiple of 8 bytes with this
  489. pad character.
  490. """
  491. if self.getMode() == ECB:
  492. # simple
  493. data = self.__key1.encrypt(data, pad)
  494. data = self.__key2.decrypt(data)
  495. return self.__key3.encrypt(data)
  496. if self.getMode() == CBC:
  497. raise "This code hasn't been tested yet"
  498. if len(data) % self.block_size != 0:
  499. raise "CBC mode needs datalen to be a multiple of blocksize (ignoring padding for now)"
  500. # simple
  501. lastblock = self.getIV()
  502. retdata = ''
  503. for i in range( 0, len(data), self.block_size ):
  504. thisblock = data[ i:i+self.block_size ]
  505. # the XOR for CBC
  506. thisblock = self.xorstr( lastblock, thisblock )
  507. thisblock = self.__key1.encrypt(thisblock)
  508. thisblock = self.__key2.decrypt(thisblock)
  509. lastblock = self.__key3.encrypt(thisblock)
  510. retdata += lastblock
  511. return retdata
  512. raise "Not reached"
  513. def decrypt(self, data, pad=''):
  514. """decrypt(data, [pad]) -> string
  515. data : String to be encrypted
  516. pad : Optional argument for decryption padding. Must only be one byte
  517. The data must be a multiple of 8 bytes and will be decrypted
  518. with the already specified key. If the optional padding character
  519. is supplied, then the un-encypted data will have the padding characters
  520. removed from the end of the string. This pad removal only occurs on the
  521. last 8 bytes of the data (last data block).
  522. """
  523. if self.getMode() == ECB:
  524. # simple
  525. data = self.__key3.decrypt(data)
  526. data = self.__key2.encrypt(data)
  527. return self.__key1.decrypt(data, pad)
  528. if self.getMode() == CBC:
  529. if len(data) % self.block_size != 0:
  530. raise "Can only decrypt multiples of blocksize"
  531. lastblock = self.getIV()
  532. retdata = ''
  533. for i in range( 0, len(data), self.block_size ):
  534. # can I arrange this better? probably...
  535. cipherchunk = data[ i:i+self.block_size ]
  536. thisblock = self.__key3.decrypt(cipherchunk)
  537. thisblock = self.__key2.encrypt(thisblock)
  538. thisblock = self.__key1.decrypt(thisblock)
  539. retdata += self.xorstr( lastblock, thisblock )
  540. lastblock = cipherchunk
  541. return retdata
  542. raise "Not reached"
  543. #############################################################################
  544. # Examples #
  545. #############################################################################
  546. def example_triple_des():
  547. from time import time
  548. # Utility module
  549. from binascii import unhexlify as unhex
  550. # example shows triple-des encryption using the des class
  551. print "Example of triple DES encryption in default ECB mode (DES-EDE3)\n"
  552. print "Triple des using the des class (3 times)"
  553. t = time()
  554. k1 = des(unhex("133457799BBCDFF1"))
  555. k2 = des(unhex("1122334455667788"))
  556. k3 = des(unhex("77661100DD223311"))
  557. d = "Triple DES test string, to be encrypted and decrypted..."
  558. print "Key1: %s" % k1.getKey()
  559. print "Key2: %s" % k2.getKey()
  560. print "Key3: %s" % k3.getKey()
  561. print "Data: %s" % d
  562. e1 = k1.encrypt(d)
  563. e2 = k2.decrypt(e1)
  564. e3 = k3.encrypt(e2)
  565. print "Encrypted: " + e3
  566. d3 = k3.decrypt(e3)
  567. d2 = k2.encrypt(d3)
  568. d1 = k1.decrypt(d2)
  569. print "Decrypted: " + d1
  570. print "DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8))
  571. print ""
  572. # Example below uses the triple-des class to achieve the same as above
  573. print "Now using triple des class"
  574. t = time()
  575. t1 = triple_des(unhex("133457799BBCDFF1112233445566778877661100DD223311"))
  576. print "Key: %s" % t1.getKey()
  577. print "Data: %s" % d
  578. td1 = t1.encrypt(d)
  579. print "Encrypted: " + td1
  580. td2 = t1.decrypt(td1)
  581. print "Decrypted: " + td2
  582. print "Triple DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8))
  583. def example_des():
  584. from time import time
  585. # example of DES encrypting in CBC mode with the IV of "\0\0\0\0\0\0\0\0"
  586. print "Example of DES encryption using CBC mode\n"
  587. t = time()
  588. k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0")
  589. data = "DES encryption algorithm"
  590. print "Key : " + k.getKey()
  591. print "Data : " + data
  592. d = k.encrypt(data)
  593. print "Encrypted: " + d
  594. d = k.decrypt(d)
  595. print "Decrypted: " + d
  596. print "DES time taken: %f (6 crypt operations)" % (time() - t)
  597. print ""
  598. def __test__():
  599. example_des()
  600. example_triple_des()
  601. def __fulltest__():
  602. # This should not produce any unexpected errors or exceptions
  603. from binascii import unhexlify as unhex
  604. from binascii import hexlify as dohex
  605. __test__()
  606. print ""
  607. k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
  608. d = k.encrypt("DES encryption algorithm")
  609. if k.decrypt(d) != "DES encryption algorithm":
  610. print "Test 1 Error: Unencypted data block does not match start data"
  611. k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
  612. d = k.encrypt("Default string of text", '*')
  613. if k.decrypt(d, "*") != "Default string of text":
  614. print "Test 2 Error: Unencypted data block does not match start data"
  615. k = des("\r\n\tABC\r\n")
  616. d = k.encrypt("String to Pad", '*')
  617. if k.decrypt(d) != "String to Pad***":
  618. print "'%s'" % k.decrypt(d)
  619. print "Test 3 Error: Unencypted data block does not match start data"
  620. k = des("\r\n\tABC\r\n")
  621. d = k.encrypt(unhex("000102030405060708FF8FDCB04080"), unhex("44"))
  622. if k.decrypt(d, unhex("44")) != unhex("000102030405060708FF8FDCB04080"):
  623. print "Test 4a Error: Unencypted data block does not match start data"
  624. if k.decrypt(d) != unhex("000102030405060708FF8FDCB0408044"):
  625. print "Test 4b Error: Unencypted data block does not match start data"
  626. k = triple_des("MyDesKey\r\n\tABC\r\n0987*543")
  627. d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
  628. if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
  629. print "Test 5 Error: Unencypted data block does not match start data"
  630. k = triple_des("\r\n\tABC\r\n0987*543")
  631. d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
  632. if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
  633. print "Test 6 Error: Unencypted data block does not match start data"
  634. def __filetest__():
  635. from time import time
  636. f = open("pyDes.py", "rb+")
  637. d = f.read()
  638. f.close()
  639. t = time()
  640. k = des("MyDESKey")
  641. d = k.encrypt(d, " ")
  642. f = open("pyDes.py.enc", "wb+")
  643. f.write(d)
  644. f.close()
  645. d = k.decrypt(d, " ")
  646. f = open("pyDes.py.dec", "wb+")
  647. f.write(d)
  648. f.close()
  649. print "DES file test time: %f" % (time() - t)
  650. def __profile__():
  651. import profile
  652. profile.run('__fulltest__()')
  653. #profile.run('__filetest__()')
  654. #if __name__ == '__main__':
  655. __test__()
  656. #__fulltest__()
  657. #__filetest__()
  658. #__profile__()
  659.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/py_compile.py", line 117, in compile
    raise py_exc
py_compile.PyCompileError: Sorry: IndentationError: unindent does not match any outer indentation level (prog.py, line 360)
stdout
Standard output is empty