Skip to content

Instantly share code, notes, and snippets.

@ejdecena
Created May 26, 2020 21:32
Show Gist options
  • Save ejdecena/031fd33e190e421917d00c9df1eafb52 to your computer and use it in GitHub Desktop.
Save ejdecena/031fd33e190e421917d00c9df1eafb52 to your computer and use it in GitHub Desktop.
Class for text ciphering.
#!/usr/bin/env python3
import base64
class CipherText:
"""Class for text ciphering."""
KEY_SECRET = "123"
@staticmethod
def encrypt(original_text: str) -> str:
enc = list()
for i, ch in enumerate(original_text):
key_c = CipherText.KEY_SECRET[i % len(CipherText.KEY_SECRET)]
enc_c = chr((ord(ch) + ord(key_c)) % 256)
enc.append(enc_c)
encrypted = base64.b64encode("".join(enc).encode()).decode("utf-8")
return encrypted
@staticmethod
def decrypt(encrypted_text: str) -> str:
dec = list()
enc = base64.b64decode(encrypted_text).decode()
for i, ch in enumerate(enc):
key_c = CipherText.KEY_SECRET[i % len(CipherText.KEY_SECRET)]
dec_c = chr((256 + ord(ch) - ord(key_c)) % 256)
dec.append(dec_c)
original_text = "".join(dec)
return original_text
if __name__ == "__main__":
# Testing ...
original_text = "Hello world! :-)"
CipherText.KEY_SECRET = "my-secret-key"
encrypted_text = CipherText.encrypt(original_text)
original_text = CipherText.decrypt(encrypted_text)
print("encrypted_text:", encrypted_text)
print("original_text:", original_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment