Ejemplo n.º 1
0
def assisstant(command):
    if command == str("Open YT"):
        scraper.youtube()
        speak("Opening Youtube")
    if command == str("Open Music app"):
        scraper.YT_music()
        speak("Opening YT Music")
    if command == str("Open Github"):
        scraper.Github()
        speak("Opening Github")
    if command == str("Enter a task = str"):
        task_input = input(str("Enter a new task: "))
        tasks.text(task_input)
        speak("Changes saved")
    if command == str("Enter a task = int"):
        task_input = input("Enter a new task: ")
        task_input_float = int(float(task_input))
        tasks.text(task_input_float)
        speak("Changes saved")
    if command == str("Encrypt"):
        encrypter_input = input(str("Enter a string to encrypt: "))
        encrypter.encrypt(bytes(encrypter_input, encoding='utf-8'))
        # encrypter_input = message
    if command == str("Decrypt"):
        decrypter_input = input(str("Enter to decrypt: "))
        encrypter.decrypt(bytes(decrypter_input, encoding='utf-8'))
    if command == str("Play some music"):
        music_choice = input(str("Should I open YT Music or Play locally?"))
        if music_choice == str("Play from YT Music"):
            scraper.YT_music()
        elif music_choice == str("Play Locally"):
            # pick an external mp3 player you have
            music.play_music(
                "/home/atif/Documents/MyProjects/Assistant/Music/Post Malone - Better Now.mp3"
            )
Ejemplo n.º 2
0
 def encrypt_decrypt(self, string, number):
     """Functionality for testing encryption and decryption"""
     encrypt_string = encrypter.encrypt(string, number)
     decrypt_string = encrypter.encrypt(encrypt_string,
                                        number,
                                        decrypt=True)
     print("Testing string: {}\nNumber: {} ".format(string, number))
     self.assertEqual(string, decrypt_string)
Ejemplo n.º 3
0
    def test_upload_encrypt_decrypt(self):

        # Read in original file contents to check against later
        original_file_str = self.local_file_as_string(
            'files_to_upload/text_file_1.txt')

        aws.upload_file('text_file_6.txt', 'file_dump/')

        # Wait for file to upload to s3 and the lambda to handle the request
        # and process the file once it has finished it should create an encrypted
        # version in processed dir
        aws.wait_for_file('processed/text_file_6.txt')

        processed_file_str = aws.get_file_as_string(
            'processed/text_file_6.txt')

        # Currently the encrypt key used is 12345678 in the live lambdas this will change
        unencrypted_file_str = encrypter.encrypt(processed_file_str,
                                                 12345678,
                                                 decrypt=True)

        print("Original str: {}\n"
              "processed str: {}\n"
              "Unencrypted str: {}".format(original_file_str,
                                           processed_file_str,
                                           unencrypted_file_str))
Ejemplo n.º 4
0
    def generate_challenges_from_csv(self, data, **kwargs):
        obj_data = []
        for d in data:
            message = self.clean_message(d['Message'])
            if not message:
                continue

            obj_data.append({
                'language': d['Language'][:2].lower(),
                'decrypted_message': message,
                'encrypted_message': encrypt(message),
                'solved': False
            })

        created = 0
        ignored = 0
        failed = 0
        for d in obj_data:
            try:
                Challenge.objects.create(**d)
                created += 1
            except IntegrityError, e:
                self.stdout.write(
                    'Warning: "%(decrypted_message)s..." already exists in challenge database. '
                    'It will be ignored.' %
                    {'decrypted_message': d['decrypted_message'][:20]})
                ignored += 1
            except Exception, e:
                print 'Warning: ', str(e)
                failed += 1
Ejemplo n.º 5
0
    def generate_challenges_from_csv(self, data, **kwargs):
        obj_data = []
        for d in data:
            message = self.clean_message(d['Message'])
            if not message:
                continue

            obj_data.append({
                'language': d['Language'][:2].lower(),
                'decrypted_message': message,
                'encrypted_message': encrypt(message),
                'solved': False
            })

        created = 0
        ignored = 0
        failed = 0
        for d in obj_data:
            try:
                Challenge.objects.create(**d)
                created += 1
            except IntegrityError, e:
                self.stdout.write(
                    'Warning: "%(decrypted_message)s..." already exists in challenge database. '
                    'It will be ignored.' % {
                        'decrypted_message': d['decrypted_message'][:20]
                    }
                )
                ignored += 1
            except Exception, e:
                print 'Warning: ', str(e)
                failed += 1
Ejemplo n.º 6
0
def sendToServer(message):
    global serverMetricIP

    message = json.dumps(message, ensure_ascii=False)
    print "Message sent: " + message

    message = encrypter.encrypt(message)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(message, (serverMetricIP, config["server"]["metric"]["port"]))
Ejemplo n.º 7
0
def store(svc, usr, pw, AES_key):
    try:
        # Generate AES encrypted password
        key = encrypter.encrypt(pw, AES_key)
        # Store in database
        db.execute(f"INSERT INTO cles (site, user, key) VALUES(?, ?, ?)",
                   (svc, usr, key))
        # Save changes into database
        db.commit()
        print(f"Password stored for service '{svc}' and user '{usr}'")
        return 0
    except:
        return 1
Ejemplo n.º 8
0
def handler(event, context):
    """Handler for when deployed as a lambda function, this should be called
     from aws when a text file is uploaded into s3 bucket"""

    # Get file key from the event
    s3_key = event['Records'][0]['s3']['object']['key']

    # Get file size
    file_size = aws.get_size_of_file(s3_key)

    memory_size = get_system_memory()

    lambda_size = aws.get_lambda_memory('Encrypt_text_files_lambda')

    print("file size: {} \n memory size: {} \n lambda_size: {}".format(
        file_size, memory_size, lambda_size))

    if file_size > (memory_size/2) or file_size > (lambda_size/2):
        print("File is too big to be dealt with by this lambda...")
        extra_mem_lambda_size = aws.get_lambda_memory('Encrypt_text_files_lambda_extra_memory')
        print("Big lmabda size {}".format(extra_mem_lambda_size))
        if file_size > (extra_mem_lambda_size/2):
            print("File is too big to be dealt with by the biggest lambda")
            raise Exception("File too big to decrypt using any known lambda")
        else:
            print('calling other lambda')
            # call other lambda
    else:
        print('encrypting file')

        # get string contents of file
        file_string = aws.get_file_as_string(s3_key)

        # encrypt
        encrypted_string = encrypter.encrypt(file_string, 12345678)

        # turn encrypted string into a file obj
        fileobj = io.BytesIO(encrypted_string.encode("utf-8"))

        # create key for encrypted file
        key = 'processed/' + s3_key.split('/')[1]

        # upload
        aws.upload_fileobj(fileobj, key)
Ejemplo n.º 9
0
def split_file(file_path, encrypt=False):
    """Takes in a file path, encrypts it if required, and outputs a set of split file path."""
    print("Split file is run")
    if not isfile(file_path):
        return
    original_file = open(file_path, 'r')
    file_contents = original_file.readlines()
    original_file.close()
    temp_paths = set()
    rel_file_path = get_rel_path(file_path)
    for i in range(0, len(file_contents)):
        temp_file_path = "/dev/shm/"+rel_file_path.replace("/", "_!_")+str(i)+".temp"
        temp_file = open(temp_file_path, 'w')
        line = file_contents[i]
        if encrypt: line = encrypt(line)
        temp_file.write(add_metatags(file_path, i, line))
        temp_file.close()
        temp_paths.add(temp_file_path)
    print(temp_paths)
    return temp_paths
Ejemplo n.º 10
0
def create_response(message_id, data):

    # subtracting header bytes fromt the buffer size
    bufferSize = BUFFER_SIZE - 4 - 1 - 1

    #calculating remaining total number of packets - 1
    fragment_remiaing = len(data) // bufferSize

    if (len(data) % bufferSize == 0 and len(data) != 0):
        fragment_remiaing = fragment_remiaing - 1

    neighbours = fragment_remiaing + 1
    id_bytes = message_id.to_bytes(4, byteorder='big')
    fragment_remiaing_bytes = fragment_remiaing.to_bytes(1, byteorder='big')
    total_packets_bytes = neighbours.to_bytes(1, byteorder="big")

    calculated_key = enc.key_calculator(message_id)
    data = enc.encrypt(calculated_key, data)

    data_bytes = data.encode('utf-8')

    bytes_to_send = id_bytes

    lis = []
    for k in range(0, len(data), bufferSize):

        end = min(len(data), (k + bufferSize))
        fragment_remiaing_bytes = fragment_remiaing.to_bytes(1,
                                                             byteorder='big')
        lis.append((bytes_to_send + total_packets_bytes +
                    fragment_remiaing_bytes + data_bytes[k:end]))
        fragment_remiaing = fragment_remiaing - 1

    if (len(lis) == 0):
        #if no record found in the database
        lis.append(bytes_to_send + (int(0)).to_bytes(1, byteorder="big") +
                   fragment_remiaing_bytes +
                   "No records found !!".encode("utf-8"))

    # returning list of packets (with headers and data)
    return lis
def handler(event, context):
    """Handler for when deployed as a lambda function, this should be called
     from aws when a text file is uploaded into s3 bucket"""
    print('encrypting file')

    # Get file key from the event
    s3_key = event['Records'][0]['s3']['object']['key']

    # get string contents of file
    file_string = aws.get_file_as_string(s3_key)

    # encrypt
    encrypted_string = encrypter.encrypt(file_string, 12345678)

    # turn encrypted string into a file obj
    fileobj = io.BytesIO(encrypted_string.encode("utf-8"))

    # create key for encrypted file
    key = 'processed/' + s3_key.split('/')[1]

    # upload
    aws.upload_fileobj(fileobj, key)
Ejemplo n.º 12
0
def encrypt():
    outputbox.delete(0.0, END)
    outputbox.insert(END, enc.encrypt(passbox.get(), msgbox.get("1.0", END)))
Ejemplo n.º 13
0
import encrypter as enc

message = raw_input("What is the message you want to encrypt/decrypt?")
randompassword = raw_input(
    "Do you want me to make a random password?\nEnter y or n.")
randompassword = randompassword.lower()
if randompassword == "y":
    password = enc.generatepassword("abcdefghijklmnopqrstuvwxyz .!;,?")
    print "Your password is:'" + password + "' It is contained in the single quotes"
else:
    password = raw_input("Copy and paste your password here:")

print "The message is:'" + enc.encrypt(
    password, message) + "' It is contained in the single quotes."