Skip to content

Commit 7ec0016

Browse files
Add files via upload
1 parent 4eb0370 commit 7ec0016

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Python/Caeser Cipher Algorithm.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'''
2+
The encryption step performed by a Caesar cipher is often incorporated as part of more complex schemes, such as the Vigenère cipher, and still has modern application in the ROT13 system. As with all single-alphabet substitution ciphers, the Caesar cipher is easily broken and in modern practice offers essentially no communications security.
3+
4+
The action of a Caesar cipher is to replace each plaintext letter with a different one a fixed number of places down the alphabet.
5+
6+
The encryption can also be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A → 0, B → 1, ..., Z → 25.[2] Encryption of a letter x by a shift n can be described mathematically as,
7+
8+
Encryption(x) = (x + n)%26
9+
Decryption(x) = (x - n)%26
10+
'''
11+
12+
'''
13+
Algorithm for Caesar Cipher:
14+
15+
Input: A String of lower case letters, called Text and an Integer between 0-25 denoting the required shift.
16+
17+
Procedure:
18+
1. Traverse the string characters.
19+
2. For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text.
20+
3. Return the new string generated.
21+
22+
To decrypt remember Cipher(n) = De-cipher(26-n)
23+
'''
24+
25+
def encrypt(plain_text, n):
26+
result = ""
27+
28+
for i in range(len(plain_text)):
29+
char = plain_text[i]
30+
31+
# Encrypt uppercase characters
32+
if (char.isupper()):
33+
result += chr((ord(char) + n-65) % 26 + 65)
34+
35+
# Encrypt lowercase characters
36+
else:
37+
result += chr((ord(char) + n - 97) % 26 + 97)
38+
39+
return result
40+
41+
def decrypt(encrypted_string, n):
42+
result = ""
43+
n = 26 - n
44+
45+
for i in range(len(encrypted_string)):
46+
char = encrypted_string[i]
47+
48+
# Encrypt uppercase characters
49+
if (char.isupper()):
50+
result += chr((ord(char) + n-65) % 26 + 65)
51+
52+
# Encrypt lowercase characters
53+
else:
54+
result += chr((ord(char) + n - 97) % 26 + 97)
55+
56+
return result
57+
58+
plain_text = "TestThisString"
59+
n = 4
60+
print("Text : ", plain_text)
61+
print("Shift : ", str(n))
62+
encrypted_string = encrypt(plain_text, n)
63+
print("Cipher: ", encrypt(plain_text, n))
64+
print("Decrypted Cipher Text: ", decrypt(encrypted_string, n))

0 commit comments

Comments
 (0)