|
1 |
| -# =============================================================== |
2 |
| -# ============ FUNCTION TO DO ASCII BASED ENCRYPTION =========== |
3 |
| -# ============ BASED ON A CERTAIN KEY =========== |
4 |
| -# ================================================================ |
| 1 | +from itertools import cycle |
5 | 2 |
|
| 3 | +def encrypt(text, key='0'): |
| 4 | + if not text: |
| 5 | + raise ValueError("Text should not be empty") |
| 6 | + if not key: |
| 7 | + raise ValueError("Key should not be empty") |
| 8 | + |
| 9 | + key = key.encode() if isinstance(key, str) else key |
| 10 | + encrypted_text = "" |
| 11 | + |
| 12 | + for char, key_char in zip(text, cycle(key)): |
| 13 | + encrypted_text += chr((ord(char) + ord(key_char)) % 128) |
| 14 | + |
| 15 | + return encrypted_text |
6 | 16 |
|
7 |
| -def encrypt(text, key=0): |
8 |
| - if not isinstance(text, str): |
9 |
| - raise TypeError("{} should be a type string".format(text)) |
10 |
| - if not isinstance(key, int): |
11 |
| - raise TypeError("{} should be of type int".format(key)) |
12 |
| - return "".join([chr(ord(something) + key) for something in text]) |
| 17 | +def decrypt(text, key='0'): |
| 18 | + if not text: |
| 19 | + raise ValueError("Text should not be empty") |
| 20 | + if not key: |
| 21 | + raise ValueError("Key should not be empty") |
| 22 | + |
| 23 | + key = key.encode() if isinstance(key, str) else key |
| 24 | + decrypted_text = "" |
| 25 | + |
| 26 | + for char, key_char in zip(text, cycle(key)): |
| 27 | + decrypted_text += chr((ord(char) - ord(key_char)) % 128) |
| 28 | + |
| 29 | + return decrypted_text |
13 | 30 |
|
| 31 | +# Example Usage: |
| 32 | +original_message = "Hello, World!" |
| 33 | +encryption_key = "secretkey" |
14 | 34 |
|
15 |
| -# =================================================================== |
16 |
| -# ============= FUNCTION TO DO ASCII BASED DECRYPTION =============== |
17 |
| -# ============= BASED ON A CERTAIN KEY =============== |
18 |
| -# =================================================================== |
| 35 | +encrypted_message = encrypt(original_message, encryption_key) |
| 36 | +print(f"Encrypted: {encrypted_message}") |
19 | 37 |
|
20 |
| - |
21 |
| -def decrypt(text, key=0): |
22 |
| - if not isinstance(text, str): |
23 |
| - raise TypeError("{} should be a type string".format(text)) |
24 |
| - if not isinstance(key, int): |
25 |
| - raise TypeError("{} should be of type int".format(key)) |
26 |
| - return "".join([chr(ord(something) - key) for something in text]) |
| 38 | +decrypted_message = decrypt(encrypted_message, encryption_key) |
| 39 | +print(f"Decrypted: {decrypted_message}") |
0 commit comments