9.12 LAB: The Caesar cipher In cryptography, Caesar's cipher is one of the simplest and most widely known encryption techniques. The method is named after Julius Caesar, who used it in his private communication. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. We wish to implement Caesar's encryption scheme by substituting each alphabet in the string with another alphabet that occurs three shifts to its left. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. Note that that the code wraps around in that A would be replaced by X, B would be replaced by Y, and C would be replaced by Z. Write a function called encrypt that takes two input arguments: the plaintext and the number of left shifts to use when constructing the cipher, and returns the encrypted string. For example, if the user enters plaintext = "I CAME I SAW I CONQUERED" and shift = 3, then

Respuesta :

Answer:

The code for the given arguements is attached as images.

Ver imagen saqib097
Ver imagen saqib097

Answer:

# the function is defined with two parameters: message and shift key

def encryptMessage(message, shift):

translated = ''

ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

message = message.upper()

for letter in message:

if letter in ALPHABET:

num = ALPHABET.find(letter)

num = num - shift

if num >= len(ALPHABET):

num = num - len(ALPHABET)

elif num < 0:

num = num + len(ALPHABET)

translated += ALPHABET[num]

else:

translated += letter

print(translated)

plaintext = str(input("Enter your plain text: "))

shift = int(input("Enter your key: "))

encryptMessage(plaintext, key)

encryptMessage('I CAME I SAW I CONQUERED', 3)

Explanation:

The code is written in Python. The logic goes below:

First translated is define as empty string to hold the encrypted text (ciphertext).

Next the entire alphabet is defined as a string constant.

Next, the received message is converted to upper case using message.upper().

Then a for-loop that goes through the entire string. Inside the for-loop is where the encryption happens. The if block check if a letter is in the ALPHABET, then it encrypt else it will just append the character to the translated (maybe space).

In the if block for encryption, we first find the index of the letter in the ALPHABET and assign it to num. Then shift is subtracted from num. If num > 26, we subtract 26 from num else if num < 0, we add 26 to num.

Next we find the letter of the alphabet with the index of num and append it to translated. Then 'translated' is displayed.

At the end of the function, we ask the user to enter a plaintext and also prompt the user to enter shift. Then the function is called using plaintext and shift as arguments.

ACCESS MORE