m2skills

ceasar cipher python

Aug 13th, 2017
1,636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. # program to implement ceasar cipher encryption
  2. import string
  3.  
  4. # this method takes string and shiftvalue as input and returns encrypted string as output
  5. def encrypt(original_msg, shift_value = 1):
  6.  
  7.     allchars = string.digits + string.ascii_letters + " " + string.punctuation
  8.  
  9.     encrypted_msg = ""
  10.  
  11.     for letter in original_msg:
  12.         if letter in allchars:
  13.             position = allchars.index(letter)
  14.             position += shift_value
  15.             position %= len(allchars)
  16.             e_letter = allchars[position]
  17.             encrypted_msg += e_letter
  18.         else:
  19.             encrypted_msg += letter
  20.  
  21.     return encrypted_msg
  22.  
  23. # method that uses the encrypt method and encrypts files by reading the file path and storing the encrypted file on desktop
  24. def encrypt_file(shift_value):
  25.     file_path = input("Enter File path : ")
  26.     try:
  27.         file1 = open(file_path, 'r+')
  28.         f2 = open("C:/Users/MOHIT/Desktop/encrypted_file.txt", 'w')
  29.         print("File opened Successfully!!")
  30.         file_data = file1.read()
  31.         print("File read Successfully!!")
  32.         encrypted_data = encrypt(file_data, shift_value)
  33.         f2.write(encrypted_data)
  34.         print("Encrypted File stored on Desktop successfully!!")
  35.  
  36.     except Exception as e:
  37.         print("Problems with opening the file")
  38.         print(str(e))
  39.  
  40. ## main function
  41.  
  42. # encrypt("hello my name is mohit" , 3)
  43. print("Program to implement Ceasar Cipher")
  44. shift_value = int(input("Enter the shift value : "))
  45. encrypt_file(shift_value)
  46. # encrypt(data)
  47.  
  48. '''
  49.  
  50. Program to implement Ceasar Cipher
  51. Enter the shift value : 5
  52. Enter File path : F:/python_3.4/sample.txt
  53. File opened Successfully!!
  54. File read Successfully!!
  55. Encrypted File stored on Desktop successfully!!
  56.  
  57. '''
Add Comment
Please, Sign In to add comment