m2skills

vignere decipher python

Sep 3rd, 2017
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. # program to implement vigenere cipher decryption
  2. import string
  3.  
  4. # method that removes symbols, letters, numbers from the message
  5. def remove_ichars(message):
  6.     other_chars = string.punctuation + string.digits + " "
  7.     n_message = "".join([i for i in message if i not in other_chars])
  8.     return n_message
  9.  
  10.  
  11. # this method takes string and shiftvalue as input and returns encrypted string as output
  12. def decrypt(original_msg, key):
  13.     index = 0
  14.     original_msg = original_msg.upper()
  15.     original_msg = remove_ichars(original_msg)
  16.     key = key.upper()
  17.     allchars = string.ascii_uppercase
  18.     decrypted_msg = ""
  19.  
  20.     for letter in original_msg:
  21.         if letter in allchars:
  22.             position = (allchars.index(letter) - allchars.index(key[index]) + 26) % len(allchars)
  23.             decrypted_msg += allchars[position]
  24.             index += 1
  25.             # reset index is greater than length of key
  26.             if index >= len(key):
  27.                 index %= len(key)
  28.         else:
  29.             decrypted_msg += letter
  30.             index = 0
  31.     return decrypted_msg
  32.  
  33.  
  34. # method that uses the decrypt method and decrypts files by reading the file path and storing the decrypted file on desktop
  35. def decrypt_file(key):
  36.     file_path = input("Enter File path : ")
  37.     try:
  38.         file1 = open(file_path, 'r+')
  39.         f2 = open("C:/Users/MOHIT/Desktop/decrypted_file.txt", 'w')
  40.         print("File opened Successfully!!")
  41.         file_data = file1.read()
  42.         print("File read Successfully!!")
  43.         decrypted_data = decrypt(file_data, key)
  44.         f2.write(decrypted_data)
  45.         print("Decrypted File stored on Desktop successfully!!")
  46.  
  47.     except Exception as e:
  48.         print("Problems with opening the file")
  49.         print(str(e))
  50.  
  51. ## main function
  52.  
  53. # encrypt("hello my name is mohit" , 3)
  54. print("Program to implement Ceasar Cipher decryption")
  55. key = input("Enter the Decryption Key : ")
  56. decrypt_file(key)
  57. # print(decrypt(data, key))
  58.  
  59. '''
  60.  
  61. Program to implement Ceasar Cipher decryption
  62. Enter File path : F:/python_3.4/sample.txt
  63. File opened Successfully!!
  64. File read Successfully!!
  65. Decrypted File stored on Desktop successfully!!
  66.  
  67. '''
Add Comment
Please, Sign In to add comment