maroph

caesar.py

Dec 2nd, 2019
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. import random
  2.  
  3. def encrypt(plaintext, offset):
  4.     ciphertext = ''
  5.     for char in plaintext:
  6.         if not char.isalpha():
  7.             ciphertext += char
  8.             continue
  9.         if char.isupper():
  10.             ciphertext += chr((ord(char) + offset - 65) % 26 + 65)
  11.         else:
  12.             ciphertext += chr((ord(char) + offset - 97) % 26 + 97)
  13.     return ciphertext
  14.  
  15. def decrypt(ciphertext, offset):
  16.     plaintext = ''
  17.     for char in ciphertext:
  18.         if not char.isalpha():
  19.             plaintext += char
  20.             continue
  21.         if char.isupper():
  22.             plaintext += chr((ord(char) - offset - 65) % 26 + 65)
  23.         else:
  24.             plaintext += chr((ord(char) - offset - 97) % 26 + 97)
  25.     return plaintext
  26.  
  27.  
  28. while True:
  29.     resp = input("Do you want to (e)ncode or (d)ecode? [e/d]:")
  30.     if resp not in ["e", "d"]:
  31.         continue
  32.     break
  33.  
  34. mode_encrypt = True
  35. if resp == "d":
  36.     mode_encrypt = False
  37.  
  38. while True:
  39.     resp = input("Do you want to use a random key? [y/n]:")
  40.     if resp not in ["y", "n"]:
  41.         continue
  42.     break
  43.  
  44. if resp == "y":
  45.     key = random.randrange(1,25)
  46.     print('random key value :', key)
  47. else:
  48.     while True:
  49.         try:
  50.             key = int(input("What key would you like to use? Enter a number between 1 and 25:"))
  51.         except:
  52.             print('input is not an integer')
  53.             continue
  54.         if key < 1 or key > 25:
  55.             print("Invalid key")
  56.             continue
  57.         break
  58.  
  59. if mode_encrypt:
  60.     plaintext = input("Enter your plaintext:")
  61.     print('plaintext  :', plaintext)
  62.     ciphertext = encrypt(plaintext, key)
  63.     print('ciphertext :', ciphertext)
  64. else:
  65.     ciphertext = input("Enter your ciphertext:")
  66.     print('ciphertext :', ciphertext)
  67.     plaintext = decrypt(ciphertext, key)
  68.     print('plaintext  :', plaintext)
Advertisement
Add Comment
Please, Sign In to add comment