Python/ciphers/caesar_cipher.py

67 lines
1.9 KiB
Python
Raw Normal View History

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