Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import random
- # Reads file located in the 'file_path' returning its content
- def read_file(file_path):
- try:
- file_wrapper = open(file_path, "rb")
- file_content = list(file_wrapper.read())
- file_wrapper.close()
- return file_content
- except IOError as io_error:
- print(f'Cant access file {file_path}', io_error)
- # Returns empty bytearray
- return []
- # Writes content to file
- def write_file(file_path, content):
- try:
- file_wrapper = open(file_path, 'wb')
- content_as_bytes = bytearray(content)
- file_wrapper.write(content_as_bytes)
- file_wrapper.close()
- return file_path
- except IOError as io_error:
- print(f'Cant access file {file_path}', io_error)
- # Returns empty path
- return ""
- # Generates a key with length min(content_length, key_length_limit)
- def generate_key(content_length, key_length_limit):
- key_length = min(content_length, key_length_limit)
- generated_key = [random.randint(0, 255) for b in range(key_length)]
- return generated_key
- # Applies a key to file content
- def encode_decode(file_content, encription_key):
- content_length = len(file_content)
- key_length = len(encription_key)
- encoded_content = []
- encoded_byte_index = 0
- while(encoded_byte_index < content_length):
- encoded_content = [
- byte ^ encription_key[encoded_byte_index % key_length] for byte in file_content
- ]
- encoded_byte_index += 1
- return encoded_content
- def main(file_path):
- # Check if file exist
- file_content = read_file(file_path)
- print('File content:', file_content)
- # Generates a random key with the specified max length
- key_max_length = 5
- generated_key = generate_key(len(file_content), key_max_length)
- print('Key content', generated_key)
- # Encodes the content using the specified key
- encoded_content = encode_decode(file_content, generated_key)
- print('Encoded content', encoded_content)
- # Writed the encoded content to a file
- encoded_file_path = write_file(file_path + '_encoded', encoded_content)
- # Reads the file just created back in memory
- file_content = read_file(encoded_file_path)
- # Decodes the file to show the inversion of the encoding
- decoded_content = encode_decode(file_content, generated_key)
- print('Decoded content from file {encoded_file_path}', decoded_content)
- if __name__ == "__main__":
- # Parsing arguments
- if(len(sys.argv) != 2):
- error_message = f'Wrong arguments amount, usage: {sys.argv[0]} [filename.ext]'
- print(error_message)
- # Passing argument filepath to main
- main(sys.argv[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement