亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁(yè) > 編程 > Python > 正文

python實(shí)現(xiàn)的DES加密算法和3DES加密算法實(shí)例

2020-01-04 18:07:55
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

這篇文章主要介紹了python實(shí)現(xiàn)的DES加密算法和3DES加密算法,以實(shí)例形式較為詳細(xì)的分析了DES加密算法和3DES加密算法的原理與實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了python實(shí)現(xiàn)的DES加密算法和3DES加密算法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

  1. ############################################################################# 
  2. # Documentation # 
  3. ############################################################################# 
  4. # Author: Todd Whiteman 
  5. # Date: 16th March, 2009 
  6. # Verion: 2.0.0 
  7. # License: Public Domain - free to do as you wish 
  8. # Homepage: http://twhiteman.netfirms.com/des.html 
  9. # 
  10. # This is a pure python implementation of the DES encryption algorithm. 
  11. # It's pure python to avoid portability issues, since most DES  
  12. # implementations are programmed in C (for performance reasons). 
  13. # 
  14. # Triple DES class is also implemented, utilising the DES base. Triple DES 
  15. # is either DES-EDE3 with a 24 byte key, or DES-EDE2 with a 16 byte key. 
  16. # 
  17. # See the README.txt that should come with this python module for the 
  18. # implementation methods used. 
  19. # 
  20. # Thanks to: 
  21. # * David Broadwell for ideas, comments and suggestions. 
  22. # * Mario Wolff for pointing out and debugging some triple des CBC errors. 
  23. # * Santiago Palladino for providing the PKCS5 padding technique. 
  24. # * Shaya for correcting the PAD_PKCS5 triple des CBC errors. 
  25. # 
  26. """A pure python implementation of the DES and TRIPLE DES encryption algorithms. 
  27. Class initialization 
  28. -------------------- 
  29. pyDes.des(key, [mode], [IV], [pad], [padmode]) 
  30. pyDes.triple_des(key, [mode], [IV], [pad], [padmode]) 
  31. key -> Bytes containing the encryption key. 8 bytes for DES, 16 or 24 bytes 
  32. for Triple DES 
  33. mode -> Optional argument for encryption type, can be either 
  34. pyDes.ECB (Electronic Code Book) or pyDes.CBC (Cypher Block Chaining) 
  35. IV -> Optional Initial Value bytes, must be supplied if using CBC mode. 
  36. Length must be 8 bytes. 
  37. pad -> Optional argument, set the pad character (PAD_NORMAL) to use during 
  38. all encrypt/decrpt operations done with this instance. 
  39. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5) 
  40. to use during all encrypt/decrpt operations done with this instance. 
  41. I recommend to use PAD_PKCS5 padding, as then you never need to worry about any 
  42. padding issues, as the padding can be removed unambiguously upon decrypting 
  43. data that was encrypted using PAD_PKCS5 padmode. 
  44. Common methods 
  45. -------------- 
  46. encrypt(data, [pad], [padmode]) 
  47. decrypt(data, [pad], [padmode]) 
  48. data -> Bytes to be encrypted/decrypted 
  49. pad -> Optional argument. Only when using padmode of PAD_NORMAL. For 
  50. encryption, adds this characters to the end of the data block when 
  51. data is not a multiple of 8 bytes. For decryption, will remove the 
  52. trailing characters that match this pad character from the last 8 
  53. bytes of the unencrypted data block. 
  54. padmode -> Optional argument, set the padding mode, must be one of PAD_NORMAL 
  55. or PAD_PKCS5). Defaults to PAD_NORMAL. 
  56.  
  57. Example 
  58. ------- 
  59. from pyDes import * 
  60. data = "Please encrypt my data" 
  61. k = des("DESCRYPT", CBC, "/0/0/0/0/0/0/0/0", pad=None, padmode=PAD_PKCS5) 
  62. # For Python3, you'll need to use bytes, i.e.: 
  63. # data = b"Please encrypt my data" 
  64. # k = des(b"DESCRYPT", CBC, b"/0/0/0/0/0/0/0/0", pad=None, padmode=PAD_PKCS5) 
  65. d = k.encrypt(data) 
  66. print "Encrypted: %r" % d 
  67. print "Decrypted: %r" % k.decrypt(d) 
  68. assert k.decrypt(d, padmode=PAD_PKCS5) == data 
  69.  
  70. See the module source (pyDes.py) for more examples of use. 
  71. You can also run the pyDes.py file without and arguments to see a simple test. 
  72. Note: This code was not written for high-end systems needing a fast 
  73. implementation, but rather a handy portable solution with small usage. 
  74. """ 
  75. import sys 
  76. # _pythonMajorVersion is used to handle Python2 and Python3 differences. 
  77. _pythonMajorVersion = sys.version_info[0
  78. # Modes of crypting / cyphering 
  79. ECB = 0 
  80. CBC = 1 
  81. # Modes of padding 
  82. PAD_NORMAL = 1 
  83. PAD_PKCS5 = 2 
  84. # PAD_PKCS5: is a method that will unambiguously remove all padding 
  85. # characters after decryption, when originally encrypted with 
  86. # this padding mode. 
  87. # For a good description of the PKCS5 padding technique, see: 
  88. # http://www.faqs.org/rfcs/rfc1423.html 
  89. # The base class shared by des and triple des. 
  90. class _baseDes(object): 
  91. def __init__(self, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): 
  92. if IV: 
  93. IV = self._guardAgainstUnicode(IV) 
  94. if pad: 
  95. pad = self._guardAgainstUnicode(pad) 
  96. self.block_size = 8 
  97. # Sanity checking of arguments. 
  98. if pad and padmode == PAD_PKCS5: 
  99. raise ValueError("Cannot use a pad character with PAD_PKCS5"
  100. if IV and len(IV) != self.block_size: 
  101. raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes"
  102. # Set the passed in variables 
  103. self._mode = mode 
  104. self._iv = IV 
  105. self._padding = pad 
  106. self._padmode = padmode 
  107. def getKey(self): 
  108. """getKey() -> bytes""" 
  109. return self.__key 
  110. def setKey(self, key): 
  111. """Will set the crypting key for this object.""" 
  112. key = self._guardAgainstUnicode(key) 
  113. self.__key = key 
  114. def getMode(self): 
  115. """getMode() -> pyDes.ECB or pyDes.CBC""" 
  116. return self._mode 
  117. def setMode(self, mode): 
  118. """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" 
  119. self._mode = mode 
  120. def getPadding(self): 
  121. """getPadding() -> bytes of length 1. Padding character.""" 
  122. return self._padding 
  123. def setPadding(self, pad): 
  124. """setPadding() -> bytes of length 1. Padding character.""" 
  125. if pad is not None
  126. pad = self._guardAgainstUnicode(pad) 
  127. self._padding = pad 
  128. def getPadMode(self): 
  129. """getPadMode() -> pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" 
  130. return self._padmode 
  131. def setPadMode(self, mode): 
  132. """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" 
  133. self._padmode = mode 
  134. def getIV(self): 
  135. """getIV() -> bytes""" 
  136. return self._iv 
  137. def setIV(self, IV): 
  138. """Will set the Initial Value, used in conjunction with CBC mode""" 
  139. if not IV or len(IV) != self.block_size: 
  140. raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes"
  141. IV = self._guardAgainstUnicode(IV) 
  142. self._iv = IV 
  143. def _padData(self, data, pad, padmode): 
  144. # Pad data depending on the mode 
  145. if padmode is None
  146. # Get the default padding mode. 
  147. padmode = self.getPadMode() 
  148. if pad and padmode == PAD_PKCS5: 
  149. raise ValueError("Cannot use a pad character with PAD_PKCS5"
  150. if padmode == PAD_NORMAL: 
  151. if len(data) % self.block_size == 0
  152. # No padding required. 
  153. return data 
  154. if not pad: 
  155. # Get the default padding. 
  156. pad = self.getPadding() 
  157. if not pad: 
  158. raise ValueError("Data must be a multiple of " + str(self.block_size) + " bytes in length. Use padmode=PAD_PKCS5 or set the pad character."
  159. data += (self.block_size - (len(data) % self.block_size)) * pad 
  160. elif padmode == PAD_PKCS5: 
  161. pad_len = 8 - (len(data) % self.block_size) 
  162. if _pythonMajorVersion < 3
  163. data += pad_len * chr(pad_len) 
  164. else
  165. data += bytes([pad_len] * pad_len) 
  166. return data 
  167. def _unpadData(self, data, pad, padmode): 
  168. # Unpad data depending on the mode. 
  169. if not data: 
  170. return data 
  171. if pad and padmode == PAD_PKCS5: 
  172. raise ValueError("Cannot use a pad character with PAD_PKCS5"
  173. if padmode is None
  174. # Get the default padding mode. 
  175. padmode = self.getPadMode() 
  176. if padmode == PAD_NORMAL: 
  177. if not pad: 
  178. # Get the default padding. 
  179. pad = self.getPadding() 
  180. if pad: 
  181. data = data[:-self.block_size] + / 
  182. data[-self.block_size:].rstrip(pad) 
  183. elif padmode == PAD_PKCS5: 
  184. if _pythonMajorVersion < 3
  185. pad_len = ord(data[-1]) 
  186. else
  187. pad_len = data[-1
  188. data = data[:-pad_len] 
  189. return data 
  190. def _guardAgainstUnicode(self, data): 
  191. # Only accept byte strings or ascii unicode values, otherwise 
  192. # there is no way to correctly decode the data into bytes. 
  193. if _pythonMajorVersion < 3
  194. if isinstance(data, unicode): 
  195. raise ValueError("pyDes can only work with bytes, not Unicode strings."
  196. else
  197. if isinstance(data, str): 
  198. # Only accept ascii unicode values. 
  199. try
  200. return data.encode('ascii'
  201. except UnicodeEncodeError: 
  202. pass 
  203. raise ValueError("pyDes can only work with encoded strings, not Unicode."
  204. return data 
  205. ############################################################################# 
  206. # DES # 
  207. ############################################################################# 
  208. class des(_baseDes): 
  209. """DES encryption/decrytpion class 
  210. Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. 
  211. pyDes.des(key,[mode], [IV]) 
  212. key -> Bytes containing the encryption key, must be exactly 8 bytes 
  213. mode -> Optional argument for encryption type, can be either pyDes.ECB 
  214. (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) 
  215. IV -> Optional Initial Value bytes, must be supplied if using CBC mode. 
  216. Must be 8 bytes in length. 
  217. pad -> Optional argument, set the pad character (PAD_NORMAL) to use 
  218. during all encrypt/decrpt operations done with this instance. 
  219. padmode -> Optional argument, set the padding mode (PAD_NORMAL or 
  220. PAD_PKCS5) to use during all encrypt/decrpt operations done 
  221. with this instance. 
  222. """ 
  223.  
  224. # Permutation and translation tables for DES 
  225. __pc1 = [5648403224168
  226. 574941332517
  227. 15850423426
  228. 10259514335
  229. 544638302214
  230. 615345372921
  231. 56052443628
  232. 1242719113 
  233. # number left rotations of pc1 
  234. __left_rotations = [ 
  235. 122222212222221 
  236. # permuted choice key (table 2) 
  237. __pc2 = [ 
  238. 16102304
  239. 27145209
  240. 18113257
  241. 62619121
  242. 5130364654
  243. 3950443247
  244. 4838553352
  245. 4149352831 
  246. # initial permutation IP 
  247. __ip = [57494133251791
  248. 5143352719113
  249. 5345372921135
  250. 5547393123157
  251. 484032241680
  252. 5042342618102
  253. 5244362820124
  254. 5446383022146 
  255. # Expansion table for turning 32 bit blocks into 48 bits 
  256. __expansion_table = [ 
  257. 01234
  258. 45678
  259. 89101112
  260. 1213141516
  261. 1617181920
  262. 2021222324
  263. 2425262728
  264. 282930310 
  265. # The (in)famous S-boxes 
  266. __sbox = [ 
  267. # S1 
  268. [1441312151183106125907
  269. 157414213110612119538
  270. 114813621115129731050
  271. 12824917511314100613], 
  272. # S2 
  273. [1518146113497213120510
  274. 134715281412011069115
  275. 147111041315812693215
  276. 81013154211671205149], 
  277. # S3 
  278. [1009146315511312711428
  279. 70934610285141211151
  280. 64981530111212510147
  281. 101306987415143115212], 
  282. # S4 
  283. [7131430691012851112415
  284. 81156150347212110149
  285. 69012117131513145284
  286. 150610113894511127214], 
  287. # S5 
  288. [2124171011685315130149
  289. 11212471315015103986
  290. 211110137815912563014
  291. 81271142136150910453], 
  292. # S6 
  293. [1211015926801334147511
  294. 15427129561131401138
  295. 141552812370410113116
  296. 321295151011141760813], 
  297. # S7 
  298. [4112141508133129751061
  299. 01174911014351221586
  300. 411131237141015680592
  301. 111381410795015142312], 
  302. # S8 
  303. [1328461511110931450127
  304. 151381037412561101492
  305. 114191214206101315358
  306. 114741081315129035611], 
  307.  
  308. # 32-bit permutation function P used on the output of the S-boxes 
  309. __p = [ 
  310. 619202811
  311. 160142225
  312. 1730917
  313. ,13312628
  314. 122952110
  315. 24 
  316. # final permutation IP^-1 
  317. __fp = [ 
  318. 7471555236331
  319. 6461454226230
  320. 5451353216129
  321. 4441252206028
  322. 3431151195927
  323. 2421050185826
  324. 141949175725
  325. 040848165624 
  326. # Type of crypting being done 
  327. ENCRYPT = 0x00 
  328. DECRYPT = 0x01 
  329. # Initialisation 
  330. def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): 
  331. # Sanity checking of arguments. 
  332. if len(key) != 8
  333. raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long."
  334. _baseDes.__init__(self, mode, IV, pad, padmode) 
  335. self.key_size = 8 
  336. self.L = [] 
  337. self.R = [] 
  338. self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16) 
  339. self.final = [] 
  340. self.setKey(key) 
  341. def setKey(self, key): 
  342. """Will set the crypting key for this object. Must be 8 bytes.""" 
  343. _baseDes.setKey(self, key) 
  344. self.__create_sub_keys() 
  345. def __String_to_BitList(self, data): 
  346. """Turn the string data, into a list of bits (1, 0)'s""" 
  347. if _pythonMajorVersion < 3
  348. # Turn the strings into integers. Python 3 uses a bytes 
  349. # class, which already has this behaviour. 
  350. data = [ord(c) for c in data] 
  351. l = len(data) * 8 
  352. result = [0] * l 
  353. pos = 0 
  354. for ch in data: 
  355. i = 7 
  356. while i >= 0
  357. if ch & (1 << i) != 0
  358. result[pos] = 1 
  359. else
  360. result[pos] = 0 
  361. pos += 1 
  362. i -= 1 
  363. return result 
  364. def __BitList_to_String(self, data): 
  365. """Turn the list of bits -> data, into a string""" 
  366. result = [] 
  367. pos = 0 
  368. c = 0 
  369. while pos < len(data): 
  370. c += data[pos] << (7 - (pos % 8)) 
  371. if (pos % 8) == 7
  372. result.append(c) 
  373. c = 0 
  374. pos += 1 
  375. if _pythonMajorVersion < 3
  376. return ''.join([ chr(c) for c in result ]) 
  377. else
  378. return bytes(result) 
  379. def __permutate(self, table, block): 
  380. """Permutate this block with the specified table""" 
  381. return list(map(lambda x: block[x], table)) 
  382. # Transform the secret key, so that it is ready for data processing 
  383. # Create the 16 subkeys, K[1] - K[16] 
  384. def __create_sub_keys(self): 
  385. """Create the 16 subkeys K[1] to K[16] from the given key""" 
  386. key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey())) 
  387. i = 0 
  388. # Split into Left and Right sections 
  389. self.L = key[:28
  390. self.R = key[28:] 
  391. while i < 16
  392. j = 0 
  393. # Perform circular left shifts 
  394. while j < des.__left_rotations[i]: 
  395. self.L.append(self.L[0]) 
  396. del self.L[0
  397. self.R.append(self.R[0]) 
  398. del self.R[0
  399. j += 1 
  400. # Create one of the 16 subkeys through pc2 permutation 
  401. self.Kn[i] = self.__permutate(des.__pc2, self.L + self.R) 
  402. i += 1 
  403. # Main part of the encryption algorithm, the number cruncher :) 
  404. def __des_crypt(self, block, crypt_type): 
  405. """Crypt the block of data through DES bit-manipulation""" 
  406. block = self.__permutate(des.__ip, block) 
  407. self.L = block[:32
  408. self.R = block[32:] 
  409. # Encryption starts from Kn[1] through to Kn[16] 
  410. if crypt_type == des.ENCRYPT: 
  411. iteration = 0 
  412. iteration_adjustment = 1 
  413. # Decryption starts from Kn[16] down to Kn[1] 
  414. else
  415. iteration = 15 
  416. iteration_adjustment = -1 
  417. i = 0 
  418. while i < 16
  419. # Make a copy of R[i-1], this will later become L[i] 
  420. tempR = self.R[:] 
  421. # Permutate R[i - 1] to start creating R[i] 
  422. self.R = self.__permutate(des.__expansion_table, self.R) 
  423. # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here 
  424. self.R = list(map(lambda x, y: x ^ y, self.R, self.Kn[iteration])) 
  425. 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:]] 
  426. # Optimization: Replaced below commented code with above 
  427. #j = 0 
  428. #B = [] 
  429. #while j < len(self.R): 
  430. # self.R[j] = self.R[j] ^ self.Kn[iteration][j] 
  431. # j += 1 
  432. # if j % 6 == 0: 
  433. # B.append(self.R[j-6:j]) 
  434. # Permutate B[1] to B[8] using the S-Boxes 
  435. j = 0 
  436. Bn = [0] * 32 
  437. pos = 0 
  438. while j < 8
  439. # Work out the offsets 
  440. m = (B[j][0] << 1) + B[j][5
  441. n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4
  442. # Find the permutation value 
  443. v = des.__sbox[j][(m << 4) + n] 
  444. # Turn value into bits, add it to result: Bn 
  445. Bn[pos] = (v & 8) >> 3 
  446. Bn[pos + 1] = (v & 4) >> 2 
  447. Bn[pos + 2] = (v & 2) >> 1 
  448. Bn[pos + 3] = v & 1 
  449. pos += 4 
  450. j += 1 
  451. # Permutate the concatination of B[1] to B[8] (Bn) 
  452. self.R = self.__permutate(des.__p, Bn) 
  453. # Xor with L[i - 1] 
  454. self.R = list(map(lambda x, y: x ^ y, self.R, self.L)) 
  455. # Optimization: This now replaces the below commented code 
  456. #j = 0 
  457. #while j < len(self.R): 
  458. # self.R[j] = self.R[j] ^ self.L[j] 
  459. # j += 1 
  460. # L[i] becomes R[i - 1] 
  461. self.L = tempR 
  462. i += 1 
  463. iteration += iteration_adjustment 
  464. # Final permutation of R[16]L[16] 
  465. self.final = self.__permutate(des.__fp, self.R + self.L) 
  466. return self.final 
  467.  
  468. # Data to be encrypted/decrypted 
  469. def crypt(self, data, crypt_type): 
  470. """Crypt the data in blocks, running it through des_crypt()""" 
  471. # Error check the data 
  472. if not data: 
  473. return '' 
  474. if len(data) % self.block_size != 0
  475. if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks 
  476. raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes/n."
  477. if not self.getPadding(): 
  478. raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes/n. Try setting the optional padding character"
  479. else
  480. data += (self.block_size - (len(data) % self.block_size)) * self.getPadding() 
  481. # print "Len of data: %f" % (len(data) / self.block_size) 
  482. if self.getMode() == CBC: 
  483. if self.getIV(): 
  484. iv = self.__String_to_BitList(self.getIV()) 
  485. else
  486. raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering"
  487. # Split the data into blocks, crypting each one seperately 
  488. i = 0 
  489. dict = {} 
  490. result = [] 
  491. #cached = 0 
  492. #lines = 0 
  493. while i < len(data): 
  494. # Test code for caching encryption results 
  495. #lines += 1 
  496. #if dict.has_key(data[i:i+8]): 
  497. #print "Cached result for: %s" % data[i:i+8] 
  498. # cached += 1 
  499. # result.append(dict[data[i:i+8]]) 
  500. # i += 8 
  501. # continue 
  502. block = self.__String_to_BitList(data[i:i+8]) 
  503. # Xor with IV if using CBC mode 
  504. if self.getMode() == CBC: 
  505. if crypt_type == des.ENCRYPT: 
  506. block = list(map(lambda x, y: x ^ y, block, iv)) 
  507. #j = 0 
  508. #while j < len(block): 
  509. # block[j] = block[j] ^ iv[j] 
  510. # j += 1 
  511. processed_block = self.__des_crypt(block, crypt_type) 
  512. if crypt_type == des.DECRYPT: 
  513. processed_block = list(map(lambda x, y: x ^ y, processed_block, iv)) 
  514. #j = 0 
  515. #while j < len(processed_block): 
  516. # processed_block[j] = processed_block[j] ^ iv[j] 
  517. # j += 1 
  518. iv = block 
  519. else
  520. iv = processed_block 
  521. else
  522. processed_block = self.__des_crypt(block, crypt_type) 
  523.  
  524. # Add the resulting crypted block to our list 
  525. #d = self.__BitList_to_String(processed_block) 
  526. #result.append(d) 
  527. result.append(self.__BitList_to_String(processed_block)) 
  528. #dict[data[i:i+8]] = d 
  529. i += 8 
  530. # print "Lines: %d, cached: %d" % (lines, cached) 
  531. # Return the full crypted string 
  532. if _pythonMajorVersion < 3
  533. return ''.join(result) 
  534. else
  535. return bytes.fromhex('').join(result) 
  536. def encrypt(self, data, pad=None, padmode=None): 
  537. """encrypt(data, [pad], [padmode]) -> bytes 
  538. data : Bytes to be encrypted 
  539. pad : Optional argument for encryption padding. Must only be one byte 
  540. padmode : Optional argument for overriding the padding mode. 
  541. The data must be a multiple of 8 bytes and will be encrypted 
  542. with the already specified key. Data does not have to be a 
  543. multiple of 8 bytes if the padding character is supplied, or 
  544. the padmode is set to PAD_PKCS5, as bytes will then added to 
  545. ensure the be padded data is a multiple of 8 bytes. 
  546. """ 
  547. data = self._guardAgainstUnicode(data) 
  548. if pad is not None
  549. pad = self._guardAgainstUnicode(pad) 
  550. data = self._padData(data, pad, padmode) 
  551. return self.crypt(data, des.ENCRYPT) 
  552. def decrypt(self, data, pad=None, padmode=None): 
  553. """decrypt(data, [pad], [padmode]) -> bytes 
  554. data : Bytes to be encrypted 
  555. pad : Optional argument for decryption padding. Must only be one byte 
  556. padmode : Optional argument for overriding the padding mode. 
  557. The data must be a multiple of 8 bytes and will be decrypted 
  558. with the already specified key. In PAD_NORMAL mode, if the 
  559. optional padding character is supplied, then the un-encrypted 
  560. data will have the padding characters removed from the end of 
  561. the bytes. This pad removal only occurs on the last 8 bytes of 
  562. the data (last data block). In PAD_PKCS5 mode, the special 
  563. padding end markers will be removed from the data after decrypting. 
  564. """ 
  565. data = self._guardAgainstUnicode(data) 
  566. if pad is not None
  567. pad = self._guardAgainstUnicode(pad) 
  568. data = self.crypt(data, des.DECRYPT) 
  569. return self._unpadData(data, pad, padmode) 
  570.  
  571. ############################################################################# 
  572. # Triple DES # 
  573. ############################################################################# 
  574. class triple_des(_baseDes): 
  575. """Triple DES encryption/decrytpion class 
  576. This algorithm uses the DES-EDE3 (when a 24 byte key is supplied) or 
  577. the DES-EDE2 (when a 16 byte key is supplied) encryption methods. 
  578. Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes. 
  579. pyDes.des(key, [mode], [IV]) 
  580. key -> Bytes containing the encryption key, must be either 16 or 
  581. bytes long 
  582. mode -> Optional argument for encryption type, can be either pyDes.ECB 
  583. (Electronic Code Book), pyDes.CBC (Cypher Block Chaining) 
  584. IV -> Optional Initial Value bytes, must be supplied if using CBC mode. 
  585. Must be 8 bytes in length. 
  586. pad -> Optional argument, set the pad character (PAD_NORMAL) to use 
  587. during all encrypt/decrpt operations done with this instance. 
  588. padmode -> Optional argument, set the padding mode (PAD_NORMAL or 
  589. PAD_PKCS5) to use during all encrypt/decrpt operations done 
  590. with this instance. 
  591. """ 
  592. def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL): 
  593. _baseDes.__init__(self, mode, IV, pad, padmode) 
  594. self.setKey(key) 
  595. def setKey(self, key): 
  596. """Will set the crypting key for this object. Either 16 or 24 bytes long.""" 
  597. self.key_size = 24 # Use DES-EDE3 mode 
  598. if len(key) != self.key_size: 
  599. if len(key) == 16# Use DES-EDE2 mode 
  600. self.key_size = 16 
  601. else
  602. raise ValueError("Invalid triple DES key size. Key must be either 16 or 24 bytes long"
  603. if self.getMode() == CBC: 
  604. if not self.getIV(): 
  605. # Use the first 8 bytes of the key 
  606. self._iv = key[:self.block_size] 
  607. if len(self.getIV()) != self.block_size: 
  608. raise ValueError("Invalid IV, must be 8 bytes in length"
  609. self.__key1 = des(key[:8], self._mode, self._iv, 
  610. self._padding, self._padmode) 
  611. self.__key2 = des(key[8:16], self._mode, self._iv, 
  612. self._padding, self._padmode) 
  613. if self.key_size == 16
  614. self.__key3 = self.__key1 
  615. else
  616. self.__key3 = des(key[16:], self._mode, self._iv, 
  617. self._padding, self._padmode) 
  618. _baseDes.setKey(self, key) 
  619. # Override setter methods to work on all 3 keys. 
  620. def setMode(self, mode): 
  621. """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" 
  622. _baseDes.setMode(self, mode) 
  623. for key in (self.__key1, self.__key2, self.__key3): 
  624. key.setMode(mode) 
  625. def setPadding(self, pad): 
  626. """setPadding() -> bytes of length 1. Padding character.""" 
  627. _baseDes.setPadding(self, pad) 
  628. for key in (self.__key1, self.__key2, self.__key3): 
  629. key.setPadding(pad) 
  630. def setPadMode(self, mode): 
  631. """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" 
  632. _baseDes.setPadMode(self, mode) 
  633. for key in (self.__key1, self.__key2, self.__key3): 
  634. key.setPadMode(mode) 
  635. def setIV(self, IV): 
  636. """Will set the Initial Value, used in conjunction with CBC mode""" 
  637. _baseDes.setIV(self, IV) 
  638. for key in (self.__key1, self.__key2, self.__key3): 
  639. key.setIV(IV) 
  640. def encrypt(self, data, pad=None, padmode=None): 
  641. """encrypt(data, [pad], [padmode]) -> bytes 
  642. data : bytes to be encrypted 
  643. pad : Optional argument for encryption padding. Must only be one byte 
  644. padmode : Optional argument for overriding the padding mode. 
  645. The data must be a multiple of 8 bytes and will be encrypted 
  646. with the already specified key. Data does not have to be a 
  647. multiple of 8 bytes if the padding character is supplied, or 
  648. the padmode is set to PAD_PKCS5, as bytes will then added to 
  649. ensure the be padded data is a multiple of 8 bytes. 
  650. """ 
  651. ENCRYPT = des.ENCRYPT 
  652. DECRYPT = des.DECRYPT 
  653. data = self._guardAgainstUnicode(data) 
  654. if pad is not None
  655. pad = self._guardAgainstUnicode(pad) 
  656. # Pad the data accordingly. 
  657. data = self._padData(data, pad, padmode) 
  658. if self.getMode() == CBC: 
  659. self.__key1.setIV(self.getIV()) 
  660. self.__key2.setIV(self.getIV()) 
  661. self.__key3.setIV(self.getIV()) 
  662. i = 0 
  663. result = [] 
  664. while i < len(data): 
  665. block = self.__key1.crypt(data[i:i+8], ENCRYPT) 
  666. block = self.__key2.crypt(block, DECRYPT) 
  667. block = self.__key3.crypt(block, ENCRYPT) 
  668. self.__key1.setIV(block) 
  669. self.__key2.setIV(block) 
  670. self.__key3.setIV(block) 
  671. result.append(block) 
  672. i += 8 
  673. if _pythonMajorVersion < 3
  674. return ''.join(result) 
  675. else
  676. return bytes.fromhex('').join(result) 
  677. else
  678. data = self.__key1.crypt(data, ENCRYPT) 
  679. data = self.__key2.crypt(data, DECRYPT) 
  680. return self.__key3.crypt(data, ENCRYPT) 
  681. def decrypt(self, data, pad=None, padmode=None): 
  682. """decrypt(data, [pad], [padmode]) -> bytes 
  683. data : bytes to be encrypted 
  684. pad : Optional argument for decryption padding. Must only be one byte 
  685. padmode : Optional argument for overriding the padding mode. 
  686. The data must be a multiple of 8 bytes and will be decrypted 
  687. with the already specified key. In PAD_NORMAL mode, if the 
  688. optional padding character is supplied, then the un-encrypted 
  689. data will have the padding characters removed from the end of 
  690. the bytes. This pad removal only occurs on the last 8 bytes of 
  691. the data (last data block). In PAD_PKCS5 mode, the special 
  692. padding end markers will be removed from the data after 
  693. decrypting, no pad character is required for PAD_PKCS5. 
  694. """ 
  695. ENCRYPT = des.ENCRYPT 
  696. DECRYPT = des.DECRYPT 
  697. data = self._guardAgainstUnicode(data) 
  698. if pad is not None
  699. pad = self._guardAgainstUnicode(pad) 
  700. if self.getMode() == CBC: 
  701. self.__key1.setIV(self.getIV()) 
  702. self.__key2.setIV(self.getIV()) 
  703. self.__key3.setIV(self.getIV()) 
  704. i = 0 
  705. result = [] 
  706. while i < len(data): 
  707. iv = data[i:i+8
  708. block = self.__key3.crypt(iv, DECRYPT) 
  709. block = self.__key2.crypt(block, ENCRYPT) 
  710. block = self.__key1.crypt(block, DECRYPT) 
  711. self.__key1.setIV(iv) 
  712. self.__key2.setIV(iv) 
  713. self.__key3.setIV(iv) 
  714. result.append(block) 
  715. i += 8 
  716. if _pythonMajorVersion < 3
  717. data = ''.join(result) 
  718. else
  719. data = bytes.fromhex('').join(result) 
  720. else
  721. data = self.__key3.crypt(data, DECRYPT) 
  722. data = self.__key2.crypt(data, ENCRYPT) 
  723. data = self.__key1.crypt(data, DECRYPT) 
  724. return self._unpadData(data, pad, padmode) 


希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
欧美影视一区在线| 日韩精品一区二区三区av| 91看片官网| 日韩美女av在线免费观看| 国产成人av一区二区三区在线| 69成人精品免费视频| 丰满爆乳一区二区三区| 亚洲精品少妇网址| 国产人与禽zoz0性伦| 色88888久久久久久影院| 国产精品久久久久久久久图文区| 日本精品裸体写真集在线观看| 国产精品天天操| 久操免费在线| 国产999精品在线观看| 中文字幕中文在线| 视频国产在线观看| 国产欧美综合一区| 18被视频免费观看视频| 国产在线观看一区二区| 国产精品永久入口久久久| 三上悠亚作品在线观看| 欧美日韩破处视频| 一区二区三区精| 欧美精品国产一区二区| 成人永久免费网站| 日本三级很黄试看120秒| japan高清日本乱xxxx| 国模精品视频| av在线亚洲一区| 日韩在线观看a| 日韩欧美黄色大片| 激情四射综合网| 91九色porn蝌蚪| 国产91精品一区二区| 美女的诞生在线观看高清免费完整版中文| 欧美在线视频在线播放完整版免费观看| 无码粉嫩虎白一线天在线观看| 久热这里有精品| 一本色道久久综合亚洲| 国产直播在线| 国产+成+人+亚洲欧洲自线| 一区二区三区免费在线| 国产伦精品一区二区三区视频网站| 一卡二卡在线视频| 亚州一区二区三区| 美女高潮视频在线看| 日韩视频在线观看一区二区| 日本亚洲色大成网站www久久| 免费电影一区二区三区| 91久色国产| 国产成人在线视频免费播放| 欧美在线不卡区| 久久久久亚洲综合| 亚洲精品第1页| 女厕嘘嘘一区二区在线播放| 精品制服美女丁香| 亚洲精品日韩久久久| 一区二区三区亚洲变态调教大结局| 日本少妇在线观看| 欧美高清视频在线观看| 麻豆精品一区二区av白丝在线| 人人爽人人av| 超碰在线12| 亚洲毛片在线免费观看| 日韩欧美精品一区二区综合视频| 日韩二区三区在线| 亚洲国产综合在线看不卡| 国产成人精品免费看在线播放| 亚洲乱码国产乱码精品精98午夜| 91网站观看| 成人啪啪18免费游戏链接| 交换国产精品视频一区| 99精品99久久久久久宅男| 在线资源免费观看| 丰满人妻一区二区三区四区53| 亚洲香蕉伊综合在人在线视看| 黄色污污网站在线观看| 国产99视频精品免视看7| 91av视频导航| 日韩系列欧美系列| 一区二区三国产精华液| 伊人中文在线| 亚洲第一网中文字幕| 大地资源中文在线观看免费版| 中文在线天堂网| 日韩欧美三级在线| 亚洲男人天堂九九视频| 国产成人啪精品视频免费网| 中文字幕一区二区三区在线播放| 亚洲成a人片在线www| 视频亚洲一区二区| 久久婷婷麻豆| 精品偷拍激情视频在线观看| 在线观看免费视频一区| 毛片在线播放a| 国产精品无码网站| 国产精品50p| 久久九九久精品国产免费直播| 日本三级中国三级99人妇网站| 国产乱人伦精品一区二区| 久久精品视频中文字幕| 无码国产精品一区二区免费式直播| 实拍女处破www免费看| 午夜欧美视频在线观看| eeuss影院eeuss最新直达| 久久久一本二本三本| 亚洲欧美综合久久久久久v动漫| 欧美亚州一区二区三区| 伊人久久大香线蕉成人综合网| 亚洲va韩国va欧美va精四季| 成+人+亚洲+综合天堂| 免费av网址在线| 欧美一区二区在线看| 最近2019中文免费高清视频观看www99| 宅男网站在线免费观看| 久久久免费高清电视剧观看| 天天草夜夜骑| 欧美日韩在线视频播放| 亚洲蜜臀av乱码久久精品| 最新av免费在线| 国产日韩视频在线观看| 99pao成人国产永久免费视频| 国产日韩欧美精品在线| 久久人妻无码一区二区| 国产av无码专区亚洲av毛网站| 精品久久人妻av中文字幕| 日韩私人影院| 久久久999精品免费| 色88久久久久高潮综合影院| 老熟妇一区二区三区| 在线视频欧美区| 亚洲天堂av一区二区三区| 婷婷激情图片久久| 色老板视频在线观看| 丰满少妇高潮在线观看| 一区二区在线免费观看| 韩国福利在线| 7878成人国产在线观看| 色噜噜狠狠一区二区三区果冻| 日韩在线免费看| 欧美综合在线视频| 裸体丰满少妇做受久久99精品| 91国偷自产一区二区开放时间| 午夜精品视频在线观看一区二区| 华人av在线| 一区二区三区免费视频播放器| 亚洲第一福利社区| 久久99热99| 麻豆视频在线观看免费网站黄| 国语精品免费视频| 欧美成人ⅴideosxxxxx| xxxxx中文字幕| 色偷偷综合社区| 国产精品观看在线亚洲人成网| 99精品国产一区二区青青牛奶| 成人中文字幕合集| 国产一级在线播放| 不卡一卡二卡三乱码免费网站| 男女啪啪免费体验区| 黄色毛片在线观看| 亚洲国产一区二区精品专区| 亚洲国产精品99| 亚洲第一久久影院| 欧美在线a视频| av软件在线观看| 3p视频在线观看| 波多野结衣片子| siro系绝美精品系列| 国产91精品不卡视频| 欧美在线一区二区三区四区| 精品国产伦理网| 久久亚洲国产精品日日av夜夜| 成人精品视频一区二区| 日韩一级欧洲| 精品少妇人妻av一区二区| 人人精品久久| 国产精品成人一区| 四虎免费在线视频| 国产日韩一区二区三免费高清| 国产精品久久欧美久久一区| 蜜臀av一区二区| 亚洲午夜久久久久| 国产大片精品免费永久看nba| 国产精品一区二区在线观看| 欧美福利视频导航| 国内精品久久久久影院色| 一区二区三区四区在线免费视频| www红色一片_亚洲成a人片在线观看_| 国产精品视频网站在线观看| 超碰在线观看97| 精品亚洲a∨一区二区三区18| 亚洲精品一区二区三区蜜桃下载| 亚洲成av人片在www色猫咪| 久久亚洲国产中v天仙www| 中文字幕资源网在线观看免费| 亚洲天堂av图片| 美女与牲口做爰视频在线观看| 亚洲国产尤物| 国内毛片久久| 国产又色又爽又黄的| 亚洲中文字幕久久精品无码喷水| 欧美一卡二卡| 亚洲二区在线播放视频| 日韩在线你懂得| 午夜久久美女| 精品人妻人人做人人爽夜夜爽| 国产乱码精品一区二区三| 国产欧美综合一区二区三区| 98视频精品全部国产| 久久精品免费av| 香蕉免费毛片视频| 亚洲最大在线视频| 欧美成人精品一区二区综合免费| 国产成人超碰人人澡人人澡| 制服丨自拍丨欧美丨动漫丨| 免费av手机在线观看| 日韩视频免费大全中文字幕| 日韩在线视频免费| 欧美精品日韩在线| av片哪里在线观看| 丝袜在线观看| 日韩经典中文字幕一区| 男女av一区三区二区色多| 久久人人爽人人爽人人片亚洲| 精品女人久久久| www.xxx亚洲| 亚洲xxxx2d动漫1| 亚洲国产成人av| wwwwxxxxx欧美| 黄色影院在线看| 日韩一区二区三区久久| 97在线观看免费高清视频| 精品伦理一区二区| 中文精品在线| 久久精品99国产精品| 国产精品粉嫩| 一个色的综合| 亚洲宅男一区| 日韩精品中文字幕第1页| 日韩人妻一区二区三区| 成人免费在线视频| 欧美激情第1页| 色在人av网站天堂精品| 国产精品伦理久久久久久| 欧美影院一区二区三区| 日本美女黄色一级片| 欧美午夜激情影院| av成人app永久免费| 乱子伦一区二区三区| 亚洲欧美成人在线| 久久久久国产精品麻豆ai换脸| 国产福利亚洲| 国产日韩一区二区在线观看| 999精品视频在线观看播放| 国产秒拍福利视频露脸| 九七伦理97伦理手机| 蜜臀av免费在线观看| 日韩免费av在线| 精品1区2区3区| 懂色av一区二区三区四区| 色综合咪咪久久网| 欧美激情精品久久久久久大尺度| 国产成人精品在线播放| 日韩视频在线观看一区二区三区| 亚洲经典自拍| 欧美做受高潮6| 亚洲四虎影院| 日韩一级高清毛片| 男人的天堂成人| 五月天婷婷影视| 中文字幕精品网| 91在线视频18| 欧美二区在线观看| 亚洲欧美色综合| 在线亚洲免费视频| 制服丝袜在线一区| 亚洲成人日韩在线| 成人短视频在线看| 宅男噜噜噜66一区二区66| 色噜噜一区二区三区| 久久精品女人天堂| 精品欧美久久| 亚洲视频 中文字幕| 亚洲最大福利网| 人人澡人人爽| 人妻精油按摩bd高清中文字幕| 成人片黄网站色大片免费毛片| 国内精品久久久久久久| 加勒比在线一区二区三区观看| 97色成人综合网站| 久久久久久人妻一区二区三区| 欧美成在线观看| 尤物yw193can在线观看| 国产suv精品一区二区四区视频| 91成人天堂久久成人| 日韩欧美四区| 国产精品电影在线观看| 日本vs亚洲vs韩国一区三区| 久久躁日日躁aaaaxxxx| 久久激情五月婷婷| 成人高清一区| 亚洲va久久久噜噜噜久久天堂| 91久久国产自产拍夜夜嗨| 91九色porny视频| 日韩精品视频网站| 中文天堂网在线www| 91干在线观看| 精品国产污污免费网站入口| 国产成人免费视频网站视频社区| av7777777| xxxxxx在线观看| 九九热播视频在线精品6| 亚洲色图首页| 少妇无码av无码专区在线观看| 美女伦理水蜜桃4| 欧美三级午夜理伦三级中文幕| 国产99一区视频免费| 国产精品美乳在线观看| 国产精品综合在线视频| 色久优优欧美色久优优| 在线播放国产精品二区一二区四区| 亚洲欧美日本一区二区| 欧美一级免费在线观看| 一二三中文字幕在线| 欧美尺度大的性做爰视频| 日本免费新一区视频| 韩日精品一区|