Crypt the data in blocks, running it through des_crypt()
(self, data, crypt_type)
| 562 | |
| 563 | # Data to be encrypted/decrypted |
| 564 | def crypt(self, data, crypt_type): |
| 565 | """Crypt the data in blocks, running it through des_crypt()""" |
| 566 | |
| 567 | # Error check the data |
| 568 | if not data: |
| 569 | return '' |
| 570 | if len(data) % self.block_size != 0: |
| 571 | if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks |
| 572 | raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.") |
| 573 | if not self.getPadding(): |
| 574 | raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character") |
| 575 | else: |
| 576 | data += (self.block_size - (len(data) % self.block_size)) * self.getPadding() |
| 577 | # print "Len of data: %f" % (len(data) / self.block_size) |
| 578 | |
| 579 | if self.getMode() == CBC: |
| 580 | if self.getIV(): |
| 581 | iv = self.__String_to_BitList(self.getIV()) |
| 582 | else: |
| 583 | raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering") |
| 584 | |
| 585 | # Split the data into blocks, crypting each one seperately |
| 586 | i = 0 |
| 587 | dict = {} |
| 588 | result = [] |
| 589 | #cached = 0 |
| 590 | #lines = 0 |
| 591 | while i < len(data): |
| 592 | # Test code for caching encryption results |
| 593 | #lines += 1 |
| 594 | #if dict.has_key(data[i:i+8]): |
| 595 | #print "Cached result for: %s" % data[i:i+8] |
| 596 | # cached += 1 |
| 597 | # result.append(dict[data[i:i+8]]) |
| 598 | # i += 8 |
| 599 | # continue |
| 600 | |
| 601 | block = self.__String_to_BitList(data[i:i+8]) |
| 602 | |
| 603 | # Xor with IV if using CBC mode |
| 604 | if self.getMode() == CBC: |
| 605 | if crypt_type == des.ENCRYPT: |
| 606 | block = [b ^ v for b, v in zip(block, iv)] |
| 607 | #j = 0 |
| 608 | #while j < len(block): |
| 609 | # block[j] = block[j] ^ iv[j] |
| 610 | # j += 1 |
| 611 | |
| 612 | processed_block = self.__des_crypt(block, crypt_type) |
| 613 | |
| 614 | if crypt_type == des.DECRYPT: |
| 615 | processed_block = [b ^ v for b, v in zip(processed_block, iv)] |
| 616 | #j = 0 |
| 617 | #while j < len(processed_block): |
| 618 | # processed_block[j] = processed_block[j] ^ iv[j] |
| 619 | # j += 1 |
| 620 | iv = block |
| 621 | else: |
no test coverage detected