Question

Write a Python program which implements the following two classical cryptosystem which we covered n class: a) Affine Cipher b

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Slulon @ АВерере기 lJKLMNoPQRSTUVIyY2N couid deve ahuman nto heliena hat t as human Alan i mukey 2013 kioms taka ent1Pt messag(D key A 1 and mode enct Sys.ex (the affhe cipher beumes incoedb se* toj. choose a difren ke twcar uohen key ATs %; set too.det decsp message Ckemessage) parnteri tt Symbol in Syon β DLS, lse; setin pin teh dee ger Random ke as1n ody 1 e) Pney.py%class vgeneve def -- int - (seuf.message, ey sef messae messeg self. ㅑ어 key det encmpy Cselp, message ,ke y) Pos lett els defdel gemessagey user me ss age final- message ohle lag saeinpu n you message f len (use message)<1 use messag conten че PorContinue else nal keys.append Creys L-6 Cont iue Plag- False cohPle f Contnue elsei lag Rals e mesage agel - messagec)eie decspted vigeneve decsupted Cmessae ke Psin(decpd) tontnue lag- fatse op44 C11npses the entee to et)

Add a comment
Answer #2

#Python program to illustate Vigenere Cipher and Affine Cipher
import sys
def gcd(a, b):
   # Everything divides 0
   if (a == 0 or b == 0):
       return 0
   # base case
   if (a == b):
       return a
   # a is greater
   if (a > b):
       return gcd(a - b, b)
   return gcd(a, b - a)

# Function to check and sys.stdout.write if
# two numbers are co-prime or not
def coprime(a, b):
if (gcd(a, b) == 1):
return True
else:
return False
def affine_encrypt(msg,a,b):
   msg = msg.upper()
   #/Cipher Text initially empty
   cipher = ""
   for i in range(len(msg)):
       char = ord(msg[i])
       # Avoid space to be encrypted
       if(msg[i]!=' '):
           ''' applying encryption formula ( a x + b ) mod m
           '''
           cipher = cipher + chr(((((a * (char - 65) ) + b) % 26) + 65))
       else:
           #else simply append space character
           cipher += msg[i]
   return cipher.lower()

def affine_decrypt(enc, a, b):
   enc = enc.upper()
   msg = ""
   a_inv = 0
   flag = 0
  
   #Find a^-1 (the multiplicative inverse of a in the group of integers modulo m.)
   for i in range(26):
       flag = (a * i) % 26
       #Check if (a*i)%26 == 1 ,then i will be the multiplicative inverse of a
       if (flag == 1):
           a_inv = i
   for i in range(len(enc)):
       char = ord(enc[i])
       if(enc[i]!=' '):
           '''Applying decryption formula a^-1 ( x - b ) mod m
           '''
           msg = msg + chr((((a_inv * ((char + 65 - b)) % 26)) + 65))
      
       else:
           #else simply append space characte
           msg += enc[i]
  
   return msg.lower()


#function that generats key from the passed string
def generate_key(inp, key):
   key = list(key)
   inp_size = len(inp)
   key_size = len(key)
   if(inp_size == key_size):
       return key
   else:
       size = inp_size - key_size
       for i in range(size):
           key.append(key[i % key_size])
   return("" . join(key))

# This function returns the
# encrypted text generated
# with the help of the key
def vigenere_encrypt(msg, key):
   msg = msg.upper()
   enc_text = []
   for i in range(len(msg)):
       key_ord = ord(key[i])
       msg_ord = ord(msg[i])

       x = ( key_ord + msg_ord) % 26
       x += 65
       enc_text.append(chr(x))
   return("" . join(enc_text)).lower()


# This function decrypts the
# encrypted text and returns
# the original text
def vigenere_decrypt(enc, key):
   enc = enc.upper()
   msg_text = []
   for i in range(len(enc)):
       enc_ord = ord(enc[i])
       key_ord = ord(key[i])
       x = ((enc_ord - key_ord) + 26) % 26
       x += 65
       msg_text.append(chr(x))
   return("" . join(msg_text)).lower()

def menu():
   sys.stdout.write("1. Affine Cipher\n")
   sys.stdout.write("2. Vigenere Cipher\n")
   sys.stdout.write("0.Exit\n")
   sys.stdout.write("Enter your choice: ")
def sub_menu():
   sys.stdout.write("\t1.Encryption\n")
   sys.stdout.write("\t2.Decryption\n")
   sys.stdout.write("\tEnter your choice: ")
#main function
def main():
   choice = 1
   msg = ""
   enc = ""
   while(choice):
       sys.stdout.write("\nCurrent Message: "+msg+" Encrypted Message: "+enc+"\n\n")
       menu()
       choice = int(input().strip())
       if(choice == 1):
           sub_menu()
           sub_ch = int(input().strip())
           if(sub_ch == 1):
               msg = input("Enter message to encrypt: ")
               a,b = map(int,input("Enter key values a and b to encrypt: ").strip().split(" "))
               if(coprime(a,26)):
                   enc = affine_encrypt(msg, a,b)
                   sys.stdout.write("\nEncrypted Message: "+enc+"\n")
               else:
                   sys.stdout.write("\nSorry the value of a must be co prime of 26"+"\n")
           elif(sub_ch == 2):
               a,b = map(int,input("Enter key values a and b to decrypt: ").strip().split(" "))
               if(enc != ""):
                   sys.stdout.write("\nDecrypted Message : "+affine_decrypt(enc, a,b)+"\n")
               else:
                   sys.stdout.write("\nSorry No Encrypted Message to decrypt")
           else:
               sys.stdout.write("\nInvalid Choice")
       elif(choice == 2):
           sub_menu()
           sub_ch = int(input().strip())
           if(sub_ch == 1):
               msg = input("Enter message to encrypt: ")
               key = input("Enter Key to encrypt: ")
               key = generate_key(msg, key)
              
               enc = vigenere_encrypt(msg, key)
               sys.stdout.write("\nEncrypted Message: "+enc)
           elif(sub_ch == 2):
               key = input("Enter Key to Decrypt: ")
               key = generate_key(msg, key)
               if(enc != ""):
                   sys.stdout.write("\nDecrypted Message : "+vigenere_decrypt(enc, key)+"\n")
               else:
                   sys.stdout.write("\nSorry No Encrypted Message to decrypt"+"\n")
           else:
               sys.stdout.write("\nInvalid Choice"+"\n")
       elif(choice == 0):
           sys.stdout.write("Exiting...")
       else:
           sys.stdout.write("\nInvalid Choice"+"\n")
main()

File Edit earch View Document Project Build Iools Help New Open ave Save All Revert CloseBack Forward Compile BuildExecute Co

Add a comment
Know the answer?
Add Answer to:
Write a Python program which implements the following two classical cryptosystem which we covered n class:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a javascript program which implements the following two classical cryptosystem which we covered in class:...

    Write a javascript program which implements the following two classical cryptosystem which we covered in class: Affine Cipher Vigenere Cipher Your program should consist of at least five functions: Two functions named encrypt, one for each of the two algorithms which accepts a lowercase alphabetical plaintext string and key as input and outputs a corresponding cipher text string. Two functions named decrypt, one for each of the two algorithms which accepts a lowercase alphabetical ciphertext string and a key as...

  • Computer Science C++ Help, here's the question that needs to be answered (TASK D): Task D....

    Computer Science C++ Help, here's the question that needs to be answered (TASK D): Task D. Decryption Implement two decryption functions corresponding to the above ciphers. When decrypting ciphertext, ensure that the produced decrypted string is equal to the original plaintext: decryptCaesar(ciphertext, rshift) == plaintext decryptVigenere(ciphertext, keyword) == plaintext Write a program decryption.cpp that uses the above functions to demonstrate encryption and decryption for both ciphers. It should first ask the user to input plaintext, then ask for a right...

  • C Program In this assignment you'll write a program that encrypts the alphabetic letters in a...

    C Program In this assignment you'll write a program that encrypts the alphabetic letters in a file using the Vigenère cipher. Your program will take two command line parameters containing the names of the file storing the encryption key and the file to be encrypted. The program must generate output to the console (terminal) screen as specified below. Command Line Parameters Your program must compile and run from the command line. The program executable must be named “vigenere” (all lower...

  • Change the following Shift Cipher program so that it uses OOP(constructor, ect.) import java.util...

    Change the following Shift Cipher program so that it uses OOP(constructor, ect.) import java.util.*; import java.lang.*; /** * * @author STEP */ public class ShiftCipher { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input = new Scanner(System.in); String plainText; System.out.print("Please enter your string: "); // get message plainText = input.nextLine(); System.out.print("Please enter your shift cipher key: "); // get s int s = input.nextInt(); int...

  • WE ARE USING PYTHON TO COMPLETE THIS ASSIGNMENT :) THANK YOU! In this programming assignment, you...

    WE ARE USING PYTHON TO COMPLETE THIS ASSIGNMENT :) THANK YOU! In this programming assignment, you will write functions to encrypt and decrypt messages using simple substitution ciphers. Your solution MUST include: a function called encode that takes two parameters: key, a 26-character long string that identifies the ciphertext mapping for each letter of the alphabet, in order; plaintext, a string of unspecified length that represents the message to be encoded. encode will return a string representing the ciphertext. a...

  • 1) Echo the input: First, you should make sure you can write a program and have...

    1) Echo the input: First, you should make sure you can write a program and have it compile and run, take input and give output. So to start you should just echo the input. This means you should prompt the user for the plaintext, read it in and then print it back out, with a message such as "this is the plaintext you entered:". [4 points, for writing a working program, echoing the input and submitting the program on the...

  • Study the VIGENÈRE CIPHER and implemented it with c++ 1.In your program, you should have two...

    Study the VIGENÈRE CIPHER and implemented it with c++ 1.In your program, you should have two functions: encryption and decryption. 2. Use any key you like. (Don't use deceptive in the slides) 3. choose a sentence or a paragraph you like as the plaintext. I have the code I just need the implementation in a different way // C++ code to implement Vigenere Cipher #include<bits/stdc++.h> using namespace std; // This function generates the key in // a cyclic manner until...

  • Using Python; Caesar part of the homework: Write c_encrypt() and c_decrypt(), both of which take two...

    Using Python; Caesar part of the homework: Write c_encrypt() and c_decrypt(), both of which take two arguments, the first one a string and the second one an integer key. Both should return a string. Vigenère part of the homework: Write vig_encrypt() and vig_decrypt() functions. Each takes two strings as inputs, with the first being the plaintext/ciphertext, and the second being the key. Both should be calling functions you wrote earlier to help make the work easier. The key will be...

  • JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information...

    JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information being exposed, it is becoming more and more important to find ways to protect our sensitive data. In this program we will develop a simple tool that helps users generate strong passwords, encrypt and decrypt data using some cyphering techniques. You will need to create two classes. The first class is your driver for the application and contains the main method. Name this class...

  • Implement in Go language AES encryption mode CBC with providing the packages name for Go language....

    Implement in Go language AES encryption mode CBC with providing the packages name for Go language. You can implement AES-ECB Mode (the basic AES) from crypto/aes package and crypto/cipher.Block. You can also get the SHA-256 hash function from crypto/sha256. You can get the secure random numbers generator from crypto/rand package. However, the you will implement both CBC mode and HMAC from scratch. You are NOT allowed to use any libraries or packages to implement these two things for you. You...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT