Python/ciphers/caesar_cipher.py

66 lines
1.9 KiB
Python
Raw Normal View History

2018-05-28 13:46:02 +00:00
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 = ''
2018-05-28 21:25:48 +00:00
while key <= 94:
2018-05-28 13:46:02 +00:00
for x in strng:
indx = (ord(x) - key) % 256
if indx < 32:
indx = indx + 95
decrypted = decrypted + chr(indx)
2018-05-28 21:25:48 +00:00
print("Key: {}\t| Message: {}".format(key, decrypted))
2018-05-28 13:46:02 +00:00
decrypted = ''
key += 1
return None
2016-07-29 07:00:38 +00:00
2016-08-02 17:46:55 +00:00
def main():
2018-05-28 13:46:02 +00:00
while True:
print('-' * 10 + "\n**Menu**\n" + '-' * 10)
print("1.Encrpyt")
print("2.Decrypt")
print("3.BruteForce")
print("4.Quit")
2018-10-20 19:45:08 +00:00
choice = input("What would you like to do?: ")
2018-05-28 13:46:02 +00:00
if choice not in ['1', '2', '3', '4']:
print("Invalid choice, please enter a valid choice")
2018-05-28 13:46:02 +00:00
elif choice == '1':
2019-02-19 15:26:09 +00:00
strng = input("Please enter the string to be encrypted: ")
key = int(input("Please enter off-set between 1-94: "))
if key in range(1, 95):
print(encrypt(strng.lower(), key))
2018-05-28 13:46:02 +00:00
elif choice == '2':
2018-10-20 19:45:08 +00:00
strng = input("Please enter the string to be decrypted: ")
key = int(input("Please enter off-set between 1-94: "))
2019-02-19 15:26:09 +00:00
if key in range(1,95):
print(decrypt(strng, key))
2018-05-28 13:46:02 +00:00
elif choice == '3':
2018-10-20 19:45:08 +00:00
strng = input("Please enter the string to be decrypted: ")
2018-05-28 13:46:02 +00:00
brute_force(strng)
main()
elif choice == '4':
print("Goodbye.")
break
if __name__ == '__main__':
main()