Amazing-Python-Scripts

Форк
0
96 строк · 2.7 Кб
1
import math
2
import sys
3
# Caesar Cipher decryption function
4

5

6
def caesar_decrypt(ciphertext, shift):
7
    plaintext = ""
8
    for char in ciphertext:
9
        if char.isalpha():
10
            ascii_offset = 65 if char.isupper() else 97
11
            decrypted_char = chr(
12
                (ord(char) - shift - ascii_offset) % 26 + ascii_offset)
13
            plaintext += decrypted_char
14
        else:
15
            plaintext += char
16
    return plaintext
17

18
# Transposition Cipher decryption function
19

20

21
def trans_decrypt(en_msg, k):
22
    message = en_msg
23
    key = k
24
    numOfColumns = int(math.ceil(len(message) / float(key)))
25
    numOfRows = k
26
    numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
27
    plaintext = [''] * numOfColumns
28
    column = 0
29
    row = 0
30
    for symbol in message:
31
        plaintext[column] += symbol
32
        column += 1  # Point to the next column.
33
        if (column == numOfColumns) or (column == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
34
            column = 0
35
            row += 1
36
    return ''.join(plaintext)
37

38
# Main program
39

40

41
def main():
42
    don_know = "[If you don't know the shift/key just press enter; the script will try all possible combinations then]"
43
    print("Welcome to the Encryption Decryption Program!")
44

45
    # Prompt user for encryption method
46
    try:
47
        method = int(input(
48
            "Which encryption method would you like to decrypt?\nChoose number\n1) Caesar\n2) Transposition\n>"))
49
    except ValueError:
50
        print("Invalid selection")
51
        sys.exit()
52

53
    # Prompt user for ciphertext
54
    ciphertext = input("Enter the ciphertext to decrypt: ")
55

56
    # Decrypt based on chosen method
57
    if method == 1 and len(ciphertext) != 0:
58
        shift = input(
59
            f"Enter the shift value used in the Caesar cipher:\n{don_know}\n>")
60

61
        if shift == '':
62
            for i in range(1, 26):
63
                plaintext = caesar_decrypt(ciphertext, i)
64
                print(plaintext)
65

66
        elif shift.isnumeric():
67
            shift = int(shift)
68
            plaintext = caesar_decrypt(ciphertext, shift)
69
            print(plaintext)
70

71
        else:
72
            print('Invalid Command')
73

74
    elif method == 2 and len(ciphertext) != 0:
75
        key = input(
76
            f"Enter the key used in the transposition cipher:\n{don_know}\n>")
77
        if key == '':
78
            for i in range(1, 26):
79
                plaintext = trans_decrypt(ciphertext, i)
80
                print(plaintext)
81

82
        elif key.isnumeric():
83
            key = int(key)
84
            plaintext = trans_decrypt(ciphertext, key)
85
            print(plaintext)
86

87
        else:
88
            print('Invalid Command')
89

90
    else:
91
        print("Invalid encryption method specified or No cipher text is given")
92

93

94
# Run the program
95
if __name__ == "__main__":
96
    main()
97

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.