def decrypt(self, ciphertext): """ Decrypts the given ciphertext with the DES cipher. Note that every operation done is lazy, returning generators rather than lists or tuples to save memory. Example: >>> cipher = DesCipher(123456) >>> cipher.decrypt('Òh*&BU¢¸') 'messageX' """ # Pad the bitstream to be evenly divisible by 64 bit chunks. Randomly choose between 0 and 1 bitstream = lazy_pad(TextBitstream(ciphertext), 64, pad_values=[0, 1]) # Chunk the bitstream into 64 bit chunks --> a tuple (L, R) of 32 bit bitstrings. chunker = DesChunker(bitstream, 32) # Run each chunk through an initial permutation. permuter = self.initial_permuter(chunker) # Lazily decrypt chunk after chunk. decrypter = self.decrypt_chunks(permuter) # Unrun each chunk through the initial permutation. permuter = self.inverse_initial_permuter(decrypter) # Now convert the above generator into a string and return it. return DesChunker.chunks_to_string(permuter)
def chunker(m, chunk_size): """ Chunker implementation. Converts the message to a series of numbers. """ for c in nslice(lazy_pad(m, chunk_size, string.ascii_lowercase), chunk_size): yield BaseRsaCipher.str2num(''.join(c))
def chunker(bitstream, chunk_size): """ Chunker implementation. Will pad the given bitstream with 0s if it is not evenly divisible by 2*chunk_size. """ for chunk in nslice(lazy_pad(bitstream, 2 * chunk_size), 2 * chunk_size): yield chunk[:chunk_size], chunk[chunk_size:]
def decrypt(self, ciphertext): """ Decrypts the given ciphertext with the DES cipher. Example: >>> cipher = ToyDesCipher(0b001001101) >>> cipher.decrypt('=Í"¨\\x88¸\\x7fßX\\x185\\x0f') 'thisisatestx' """ # Pad the ciphertext to ensure that there is the right number of bits in the ciphertext ciphertext = lazy_pad(ciphertext, 3, string.printable) # Convert the ciphertext to a bitstream. bitstream = TextBitstream(ciphertext) # Chunk the bitstream into 12 bit chunks --> a tuple (L, R) of 6 bit bitstrings. chunker = DesChunker(bitstream, 6) # Lazily decrypt chunk after chunk decrypter = self.decrypt_chunks(chunker) # Now convert the above generator into a string and return it. return DesChunker.chunks_to_string(decrypter)
def encrypt(self, message): """ Encrypts the given message with the DES cipher. Example: >>> cipher = ToyDesCipher(0b001001101) >>> cipher.encrypt('thisisatestx') '=Í"¨\\x88¸\\x7fßX\\x185\\x0f' """ # Pad the message to ensure that there is the right number of bits in the message message = lazy_pad(message, 3, string.printable) # Convert the message to a bitstream. bitstream = TextBitstream(message) # Chunk the bitstream into 12 bit chunks --> a tuple (L, R) of 6 bit bitstrings. chunker = DesChunker(bitstream, 6) # Lazily encrypt chunk after chunk. encrypter = self.encrypt_chunks(chunker) # Now convert the above generator into a string and return it. return DesChunker.chunks_to_string(encrypter)