Question

In: Computer Science

Cryptography - please use Python to complete the following task. You don't have to implement AES...

Cryptography - please use Python to complete the following task. You don't have to implement AES just import the necessary libraries. Can you fix my code? Thanks!

  1. Read in a 128 bit key from the user (16 characters). If the user enters a key of any other size it's fine to terminate the program with an error.
  2. Read in a string of arbitary length from the user. (ie, the string could be 1 character, or 50,000, or anywhere in between).
  3. Using only built in libraries of your language of choice, encrypt the string with the key using AES 128 bit with CBC.
  4. You'll need to pass an IV to your library. Create an IV of all 0's (ie 0000000000000000).
  5. If necessary convert the result to Hex, and print it to the screen.
  6. Ensure you test with a few different string.

Here is my code so far:

# Import implementation of the AES encryption
import pyaes
import binascii
import base64

# Convert output to hex format
def getHexFormat(input):
    input = input.upper()
    temp = ""

    for count in range(0, len(input)):
     temp = temp + input[count]
    if count%2 == 1:
     temp = temp + " "
    return temp

# Encryption function
def encrypt():

    # Prompt user input - key and message
    key = input("Please enter a 16 character key: ")
    if (len(str(key)) != 16):
        print("Invalid input, try again.")
        return()
    else:
        keyCipher = bytes(key, 'utf-8')
        keyHex = keyCipher.hex()
        message = input("Please enter a message: ")

        IV = os.urandom(16)
        binascii.hexlify(IV).upper()

        firstEleObj = AES.new(key, AES.MODE_CBC, IV = IV)
        messageCipher = bytes(message, 'utf-8')
        messageHex = messageCipher.hex()

        padded = messageCipher.rjust(80)
        data = firstEleObj.encrypt(padded)

        return(data)

# Print results in hexadecimal format
print("Key in hex:",getHexFormat(keyHex))
print("Message in hex:", getHexFormat(messageHex))
print("Encrypted hex:" , getHexFormat(data.hex()))

Solutions

Expert Solution

Changes.

1. the AES.new function is depricated will need to use pyaes.AESModeOfOperationCBC(key,VI)

2. The AESModeOfOperationCBC(key,VI) function only accepts a 16bit plaintext. to solve this we use a feed().

3. The AESModeOfOperationCBC function accepts key and VI as bytes and not Hex. all the lines not needed are commented out.

4. added length check for message.

5. have also properly indented the getHexFormat()

6. In your main code there was another error at the end you were not calling the encrypt() function.

# my changes 


# Import implementation of the AES encryption
from pyaes  import AES
import binascii
import base64
import os

# Convert output to hex format
def getHexFormat(input):
    input = input.upper()
    temp = ""

    for count in range(0, len(input)):
         temp = temp + input[count]
         if count%2 == 1:
             temp = temp + " "
    return temp


# Encryption function
def encrypt():
    # Prompt user input - key and message
    key = input("Please enter a 16 character key: ")

    
    if (len(key) != 16):
        print("Invalid input, try again.")
        return()
    else:
        
        keyCipher = bytes(key, 'utf-8')
        

        #  keyHex = keyCipher.hex() # no need to convert to hex the aes function accepts  bytes
        
        
        message = input("Please enter a message: ")
        
        
        #message must be from 16 to 50000 , otherwise the aes algo. gives error
        
        if len(message) < 16 or len(message) > 50000:
        
             print("Invalid message length, must be 16 - 50,000 chars long... try again.")
             return 
            
        
        

        IV = os.urandom(16)
        
#         IV = binascii.hexlify(IV).upper() no need to conver to hex.
        
        firstEleObj = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(keyCipher, iv = IV))
        
        
        ciphertext = firstEleObj.feed (message)  
        
        ciphertext += firstEleObj.feed()
        
#         messageCipher = bytes(message, 'utf-8') no need to convert 
        
#         messageHex = messageCipher.hex() 

#         padded = messageCipher.rjust(80)
        
        

        
        # converting data to hex optional 
        
        ciphertext = ciphertext.hex()
        
        
        data = getHexFormat(ciphertext)
        
        return data
    
    

ciphertext = encrypt()    

print(ciphertext)
    
   

Output : I have not changed the logic getHexFormat function.

If you find this useful then please upVote .

********************************************end**********************************


Related Solutions

Please write a python code for the following. Use dictionaries and list comprehensions to implement the...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the functions defined below. You are expected to re-use these functions in implementing other functions in the file. Include a triple-quoted string at the bottom displaying your output. Here is the starter outline for the homework: a. def count_character(text, char): """ Count the number of times a character occurs in some text. Do not use the count() method. """ return 0 b. def count_sentences(text): """...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the functions defined below. You are expected to re-use these functions in implementing other functions in the file. Include a triple-quoted string at the bottom displaying your output. Here is the starter outline for the homework: g. def big_words(text, min_length=10): """ Return a list of big words whose length is at least min_length """ return [] h. def common_words(text, min_frequency=10): """ Return words occurring at...
how can we use cryptography libraries in Python
how can we use cryptography libraries in Python
I have to use a sentinel while loop to complete the following task in a java...
I have to use a sentinel while loop to complete the following task in a java program, I want to see how this is executed so I can better understand how the sentinel while loop works. Thank you! Convert Lab 10 from a counter controlled WHILE loop to a sentinel WHILE loop. Do the following: Prompts the user to enter a grade or a -1 to quit. IF the user entered a -1 THEN Display a message that the User...
Java/Python/C++ Assignment Write a program to implement one round of AES-128 Input is the key and...
Java/Python/C++ Assignment Write a program to implement one round of AES-128 Input is the key and plaintext a. Show the plaintext as a 4x4 matrix b. Show the result after adding RoundKey0 c. Show the result after SubBytes d. Show the result after ShiftRows e. Show the result after MixColumns f. Show the result after first round
Cryptography and Applications 1. Write Python program to implement Caesar’s Cipher. Take user input to get...
Cryptography and Applications 1. Write Python program to implement Caesar’s Cipher. Take user input to get plain text and key. 2.  Write a Python program to implement Vignere Cipher. Take user input to get plain text and key. TRY TO MAKE IT AS EASY AS YOU CAN.
Cryptography and Applications 1. Write Python program to implement Caesar’s Cipher. Take user input to get...
Cryptography and Applications 1. Write Python program to implement Caesar’s Cipher. Take user input to get plain text and key. 2.  Write a Python program to implement Vignere Cipher. Take user input to get plain text and key. TRY TO MAKE IT AS EASY AS YOU CAN.
Please in C++ I don't have the binarySearchTree (Carrano) Implement the code of the BinarySeachTree Class...
Please in C++ I don't have the binarySearchTree (Carrano) Implement the code of the BinarySeachTree Class to solve: (Gaddis) Programming Challenger 3. Car Class p. 802 Ch. 13 • Implement a menu of options • Add a motor vehicle to the tree • Remove a motor vehicle to the tree • Search by vehicle model • Vehicle Inventory Updates • Take one of the tours to verify the contents of the tree. Car Class Write a class named Car that...
I did the complete programming in python , just want to use tkinter for GUI. please...
I did the complete programming in python , just want to use tkinter for GUI. please look at the 2nd part . i did some part of this program using tkinter but could not finis it. Thank you. import random image = 'w' # modified functions which accepts two numbers each and returns the respective # output def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def kidCalc():...
Implementing a cryptosystem: Choose one of the following cryptography techniques and implement it using any programming...
Implementing a cryptosystem: Choose one of the following cryptography techniques and implement it using any programming language you prefer. Your program should provide the user with two options Encryption and Decryption, with a simple UI to get the input from the user, and view the result. You can use any restriction you need for the user input but you need to clarify that and validate the user input base on your restriction. ● Feistel ● Keyword columnar ● Any cryptosystem...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT