-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext_encryption.py
More file actions
60 lines (40 loc) · 2.24 KB
/
text_encryption.py
File metadata and controls
60 lines (40 loc) · 2.24 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Caesar Cipher Implementation in Python
# Define the function to encrypt/decrypt text
def caesar_cipher(text, key_value, mode='encrypt'):
"""Encrypts or decrypts text using the Caesar Cipher. Caesar Cipher shifts each letter by a fixed number (key_value)."""
result = ''
# Reverse the shift for decryption
if mode == 'decrypt':
key_value = -key_value
# Ensure the shift is within 1-25 range (1-25 means in alphabetincal order.)
for char in text:
# Check if the character is a letter
if char.isalpha():
# Determine the starting character (A or a)
start = ord('A') if char.isupper() else ord('a')
# ord function gets the ASCII value of the character.
# 1. Convert letter to a number (0-25)
# 2. Add the shift value
# 3. Use the modulus operator (%) to wrap around the alphabet (A-Z)
# 4. Convert the number back to a letter
new_char_code = (ord(char) - start + key_value) % 26 + start
# % 26 ensures that if we go past 'Z' or 'z', we wrap around to the beginning of the alphabet.
result += chr(new_char_code)
else:
# Keep non-alphabetic characters (like spaces, numbers, punctuation) as they are
result += char
return result
# Example usage:
'''(plaintext means user input text which we want to encrypt/decrypt),(ciphertext means encrypted text),
(encryption_key means the number by which we want to shift the letters)'''
# 1. Define the plaintext and the key (shift value)
plaintext = input("Enter the text:\t\n")
encryption_key = int(input("Enter the key:\t\n")) # The key must be a number
print(f"Original Text: {plaintext}")
# 2. Encryption
ciphertext = caesar_cipher(plaintext, encryption_key, mode='encrypt')
print(f"Encrypted Text: {ciphertext}")
# 3. Decryption
decrypted_text = caesar_cipher(ciphertext, encryption_key, mode='decrypt')
print(f"Decrypted Text: {decrypted_text}")
# In simple terms, This works on an simple logic of shifting letters by a fixed number in the alphabet.By using ASCII values we can easily manipulate the characters.