summary refs log tree commit diff stats
path: root/python/code/10_caeser_cipher.py
blob: 64b1a60d426aef418a37650740e57403fc3e34af (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import sys
message = input('Enter message: ')
key = None
try:
    key = int(input('Enter key (1-25, -1 - -25): '))
except ValueError:
    print('Invalid key, must be an integer')
    sys.exit(1)

if key < 0: key += 26
if not (1 <= key <= 25):
    print('Invalid key, must be an integer with absolute value between 1 and 25, inclusive')
    sys.exit(2)

marr = bytearray(message, 'ascii')
for i in range(len(marr)):
    c = marr[i]
    if 64 < c < 64 + 27:
        c = ((c - 65) + key) % 26 + 65
    elif 96 < c < 96 + 27:
        c = ((c - 97) + key) % 26 + 97
    marr[i] = c

print('Caesar cipher with k =', key, 'applied to the given message:')
print(str(marr, encoding='ascii'))