m2skills

vignere cipher python

Sep 3rd, 2017
2,752
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. # program to implement ceasar cipher encryption
  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 encrypt(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.     encrypted_msg = ""
  19.  
  20.     for letter in original_msg:
  21.         if letter in allchars:
  22.             position = ( allchars.index(letter) + allchars.index(key[index]) ) % len(allchars)
  23.             encrypted_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.             encrypted_msg += letter
  30.             index = 0
  31.     return encrypted_msg
  32.  
  33.  
  34. # method that uses the encrypt method and encrypts files by reading the file path and storing the encrypted file on desktop
  35. def encrypt_file(key):
  36.     file_path = input("Enter File path : ")
  37.     try:
  38.         file1 = open(file_path, 'r+')
  39.         f2 = open("C:/Users/MOHIT/Desktop/encrypted_file.txt", 'w')
  40.         print("File opened Successfully!!")
  41.         file_data = file1.read()
  42.         print("File read Successfully!!")
  43.         encrypted_data = encrypt(file_data, key)
  44.         f2.write(encrypted_data)
  45.         print("Encrypted 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")
  55. data = "This is program for vignere cipher"
  56. key = input("Enter the Encryption key : ")
  57. encrypt_file(key)
  58. # print(encrypt(data, key))
  59.  
  60. '''
  61.  
  62. Program to implement Ceasar Cipher
  63. Enter File path : F:/python_3.4/sample.txt
  64. File opened Successfully!!
  65. File read Successfully!!
  66. Encrypted File stored on Desktop successfully!!
  67.  
  68. '''
Add Comment
Please, Sign In to add comment