Merge pull request #305 from PyDevthon/patch-1

Updated_caesar_cipher.py
This commit is contained in:
Harshil 2018-05-28 23:26:03 +02:00 committed by GitHub
commit 192ba078dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,45 +1,68 @@
from __future__ import print_function import sys
# The Caesar Cipher Algorithm def encrypt(strng, key):
encrypted = ''
for x in strng:
indx = (ord(x) + key) % 256
if indx > 126:
indx = indx - 95
encrypted = encrypted + chr(indx)
return encrypted
def decrypt(strng, key):
decrypted = ''
for x in strng:
indx = (ord(x) - key) % 256
if indx < 32:
indx = indx + 95
decrypted = decrypted + chr(indx)
return decrypted
def brute_force(strng):
key = 1
decrypted = ''
while key <= 94:
for x in strng:
indx = (ord(x) - key) % 256
if indx < 32:
indx = indx + 95
decrypted = decrypted + chr(indx)
print("Key: {}\t| Message: {}".format(key, decrypted))
decrypted = ''
key += 1
return None
def main(): def main():
message = input("Enter message: ") print('-' * 10 + "\n**Menu**\n" + '-' * 10)
key = int(input("Key [1-26]: ")) print("1.Encrpyt")
mode = input("Encrypt or Decrypt [e/d]: ") print("2.Decrypt")
print("3.BruteForce")
if mode.lower().startswith('e'): print("4.Quit")
mode = "encrypt" while True:
elif mode.lower().startswith('d'): choice = input("What would you like to do?: ")
mode = "decrypt" if choice not in ['1', '2', '3', '4']:
print ("Invalid choice")
translated = encdec(message, key, mode) elif choice == '1':
if mode == "encrypt": strng = input("Please enter the string to be ecrypted: ")
print(("Encryption:", translated)) while True:
elif mode == "decrypt": key = int(input("Please enter off-set between 1-94: "))
print(("Decryption:", translated)) if key in range(1, 95):
print (encrypt(strng, key))
def encdec(message, key, mode): main()
message = message.upper() elif choice == '2':
translated = "" strng = input("Please enter the string to be decrypted: ")
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" while True:
for symbol in message: key = int(input("Please enter off-set between 1-94: "))
if symbol in LETTERS: if key > 0 and key <= 94:
num = LETTERS.find(symbol) print(decrypt(strng, key))
if mode == "encrypt": main()
num = num + key elif choice == '3':
elif mode == "decrypt": strng = input("Please enter the string to be decrypted: ")
num = num - key brute_force(strng)
main()
if num >= len(LETTERS): elif choice == '4':
num -= len(LETTERS) print ("Goodbye.")
elif num < 0: sys.exit()
num += len(LETTERS)
translated += LETTERS[num]
else:
translated += symbol
return translated
if __name__ == '__main__':
import doctest
doctest.testmod()
main() main()