Crypt the block of data through DES bit-manipulation
(self, block, crypt_type)
| 483 | |
| 484 | # Main part of the encryption algorithm, the number cruncher :) |
| 485 | def __des_crypt(self, block, crypt_type): |
| 486 | """Crypt the block of data through DES bit-manipulation""" |
| 487 | block = self.__permutate(des.__ip, block) |
| 488 | self.L = block[:32] |
| 489 | self.R = block[32:] |
| 490 | |
| 491 | # Encryption starts from Kn[1] through to Kn[16] |
| 492 | if crypt_type == des.ENCRYPT: |
| 493 | iteration = 0 |
| 494 | iteration_adjustment = 1 |
| 495 | # Decryption starts from Kn[16] down to Kn[1] |
| 496 | else: |
| 497 | iteration = 15 |
| 498 | iteration_adjustment = -1 |
| 499 | |
| 500 | i = 0 |
| 501 | while i < 16: |
| 502 | # Make a copy of R[i-1], this will later become L[i] |
| 503 | tempR = self.R[:] |
| 504 | |
| 505 | # Permutate R[i - 1] to start creating R[i] |
| 506 | self.R = self.__permutate(des.__expansion_table, self.R) |
| 507 | |
| 508 | # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here |
| 509 | self.R = [b ^ k for b, k in zip(self.R, self.Kn[iteration])] |
| 510 | 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:]] |
| 511 | # Optimization: Replaced below commented code with above |
| 512 | #j = 0 |
| 513 | #B = [] |
| 514 | #while j < len(self.R): |
| 515 | # self.R[j] = self.R[j] ^ self.Kn[iteration][j] |
| 516 | # j += 1 |
| 517 | # if j % 6 == 0: |
| 518 | # B.append(self.R[j-6:j]) |
| 519 | |
| 520 | # Permutate B[1] to B[8] using the S-Boxes |
| 521 | j = 0 |
| 522 | Bn = [0] * 32 |
| 523 | pos = 0 |
| 524 | while j < 8: |
| 525 | # Work out the offsets |
| 526 | m = (B[j][0] << 1) + B[j][5] |
| 527 | n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4] |
| 528 | |
| 529 | # Find the permutation value |
| 530 | v = des.__sbox[j][(m << 4) + n] |
| 531 | |
| 532 | # Turn value into bits, add it to result: Bn |
| 533 | Bn[pos] = (v & 8) >> 3 |
| 534 | Bn[pos + 1] = (v & 4) >> 2 |
| 535 | Bn[pos + 2] = (v & 2) >> 1 |
| 536 | Bn[pos + 3] = v & 1 |
| 537 | |
| 538 | pos += 4 |
| 539 | j += 1 |
| 540 | |
| 541 | # Permutate the concatination of B[1] to B[8] (Bn) |
| 542 | self.R = self.__permutate(des.__p, Bn) |