Tuesday, April 27, 2021

Linguistics and Information Theory

Encrypting and decrypting data with python crypto library (in spyder)


#%%
from cryptography.fernet import Fernet

def write_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("key.key", "wb") as key_file:
        key_file.write(key)
        
def load_key():
    """
    Loads the key from the current directory named `key.key`
    """
    return open("key.key", "rb").read()

# generate and write a new key
write_key()

# load the previously generated key
key = load_key()

#%%
message = "Hello World!".encode()

# initialize the Fernet class
f = Fernet(key)

#%%
# encrypt the message
encrypted = f.encrypt(message)

#%%
# print how it looks
print(encrypted)

#%%
decrypted_encrypted = f.decrypt(encrypted)
print(decrypted_encrypted)
#%%
Build a simple message encoder:

from cryptography.fernet import Fernet

def write_key():
    """
    This generates a key and saves it into a file
    """
    key = Fernet.generate_key()
    with open("key.key", "wb") as key_file:
        key_file.write(key)
        
def load_key():
    """
    This loads the key from the current directory named `key.key`
    """
    return open("key.key", "rb").read()

def encrypt_message(message):
    """
    Encrypts a message
    """
    key = load_key()
    encoded_message = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_message)

    print(encrypted_message)

if __name__ == "__main__":
    encrypt_message("message to encrypt")


Output:
b'gAAAAABgh68zeqW0pQgDTZlZs-1ezzDCAHkz5SnPYKuFIrLJ8bgwHuZoJONFMShSBKLP1Xh5cjf9wLB_TbluMQ1MNRpNDs5n7UlSVa7obfaHtfCnc_FWuzA='
Build a simple decoder:

from cryptography.fernet import Fernet

def load_key():
    """
    This loads the key from the current directory named `key.key`
    """
    return open("key.key", "rb").read()

def decrypt_message(encrypted_message):
    """
    Decrypts an encrypted message
    """
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message)

    print(decrypted_message.decode())

if __name__ == "__main__":
    decrypt_message(b'gAAAAABgh68zeqW0pQgDTZlZs-1ezzDCAHkz5SnPYKuFIrLJ8bgwHuZoJONFMShSBKLP1Xh5cjf9wLB_TbluMQ1MNRpNDs5n7UlSVa7obfaHtfCnc_FWuzA=')


Output:
message to encrypt

CSV phonebook program with simple ui menu in python


import os
import csv


phones = []
name_pos = 0
phone_pos = 1
phone_header = [ 'Name', 'Phone Number']

def proper_menu_choice(which): # decides whether input is a member of phones
    if not which.isdigit():
        print ("'" + which + "' needs to be the number of a phone!")
        return False
    which = int(which)
    if which < 1 or which > len(phones):
        print ("'" + str(which) + "' needs to be the number of a phone!")
        return False
    return True
    
def delete_phone(which): # deletes a member of phones
    if not proper_menu_choice(which):
        return
    which = int(which)

    del phones[which-1]
    print( "Deleted phone #", which)

def edit_phone(which): # allows to edit a member of phones
    if not proper_menu_choice(which):
        return
    which = int(which)
        
    phone = phones[which-1]
    print("Enter the data for a new phone. Press  to leave unchanged.")
    
    print(phone[name_pos])
    newname = input("Enter phone name to change or press return: ")
    if newname == "":
        newname = phone[name_pos]
        
    print(phone[phone_pos])    
    newphone_num = input("Enter new phone number to change or press return: ")
    if newphone_num == "":
        newphone_num = phone[phone_pos]
            
    phone = [newname, newphone_num]
    phones[which-1] = phone

  
def save_phone_list(): # writes members of phones to csv file

    f = open("myphones.csv", 'w', newline='')
    for item in phones:
        csv.writer(f).writerow(item)
    f.close()
  
def load_phone_list(): # creates phones list from csv file
    if os.access("myphones.csv",os.F_OK):
        f = open("myphones.csv")
        for row in csv.reader(f):
            phones.append(row)
        f.close()

def show_phones(): # prints contents of phones list
    show_phone(phone_header, "")
    index = 1
    for phone in phones:
        show_phone(phone, index)
        index = index + 1
    print()

def show_phone(phone, index): # formats the output of show_phones(), above
    outputstr = "{0:>3}  {1:<20}  {2:>16}"
    print(outputstr.format(index, phone[name_pos], phone[phone_pos]))

def create_phone(): # appends new name/number to phones list
    print("Enter the data for a new phone:")
    newname = input("Enter name: ")
    newphone_num = input("Enter phone number: ")
    phone = [newname,newphone_num]
    phones.append(phone)
    
def menu_choice(): # simple ui menu
    """ Find out what the user wants to do next. """
    print("Choose one of the following options?")
    print("   s) Show")
    print("   n) New")
    print("   d) Delete")
    print("   e) Edit")
    print("   r) Reorder")
    print("   q) Quit")
    choice = input("Choice: ")    
    if choice.lower() in ['n','d', 's','e', 'r', 'q']:
        return choice.lower()
    else:
        print(choice +"?")
        print("Invalid option")
        return None
    
def reorder_phones():
    global phones       # this insures that we use the one at the top
    phones.sort() # replace this pass (a do-nothing) statement with your code


def main_loop():
    
    load_phone_list()
    
    while True:
        choice = menu_choice()
        if choice == None:
            continue
        if choice == 'q':
            print( "Exiting...")
            break     # jump out of while loop
        elif choice == 'n':
            create_phone()
        elif choice == 'd':
            which = input("Which item do you want to delete? ")
            print("which is ", which)
            delete_phone(which)
        elif choice == 's':
            show_phones()
        elif choice == 'e':
            which = input("Which item do you want to edit? ")
            print("which is ", which)
            edit_phone(which)
        elif choice == 'r':
            reorder_phones()
        else:
            print("Invalid choice.")
            
    save_phone_list()
    

# The following makes this program start running at main_loop() 
# when executed as a stand-alone program.    
if __name__ == '__main__':
    main_loop()

Linguistics and Information Theory