Amazing-Python-Scripts
96 строк · 2.7 Кб
1import math2import sys3# Caesar Cipher decryption function
4
5
6def caesar_decrypt(ciphertext, shift):7plaintext = ""8for char in ciphertext:9if char.isalpha():10ascii_offset = 65 if char.isupper() else 9711decrypted_char = chr(12(ord(char) - shift - ascii_offset) % 26 + ascii_offset)13plaintext += decrypted_char14else:15plaintext += char16return plaintext17
18# Transposition Cipher decryption function
19
20
21def trans_decrypt(en_msg, k):22message = en_msg23key = k24numOfColumns = int(math.ceil(len(message) / float(key)))25numOfRows = k26numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)27plaintext = [''] * numOfColumns28column = 029row = 030for symbol in message:31plaintext[column] += symbol32column += 1 # Point to the next column.33if (column == numOfColumns) or (column == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):34column = 035row += 136return ''.join(plaintext)37
38# Main program
39
40
41def main():42don_know = "[If you don't know the shift/key just press enter; the script will try all possible combinations then]"43print("Welcome to the Encryption Decryption Program!")44
45# Prompt user for encryption method46try:47method = int(input(48"Which encryption method would you like to decrypt?\nChoose number\n1) Caesar\n2) Transposition\n>"))49except ValueError:50print("Invalid selection")51sys.exit()52
53# Prompt user for ciphertext54ciphertext = input("Enter the ciphertext to decrypt: ")55
56# Decrypt based on chosen method57if method == 1 and len(ciphertext) != 0:58shift = input(59f"Enter the shift value used in the Caesar cipher:\n{don_know}\n>")60
61if shift == '':62for i in range(1, 26):63plaintext = caesar_decrypt(ciphertext, i)64print(plaintext)65
66elif shift.isnumeric():67shift = int(shift)68plaintext = caesar_decrypt(ciphertext, shift)69print(plaintext)70
71else:72print('Invalid Command')73
74elif method == 2 and len(ciphertext) != 0:75key = input(76f"Enter the key used in the transposition cipher:\n{don_know}\n>")77if key == '':78for i in range(1, 26):79plaintext = trans_decrypt(ciphertext, i)80print(plaintext)81
82elif key.isnumeric():83key = int(key)84plaintext = trans_decrypt(ciphertext, key)85print(plaintext)86
87else:88print('Invalid Command')89
90else:91print("Invalid encryption method specified or No cipher text is given")92
93
94# Run the program
95if __name__ == "__main__":96main()97