Skip to main content

How to Implement "Clear Code Encryption" in Python

"Clear Code Encryption" is a historical method used in early telegraph communication systems. It relies on a simple yet effective algorithm: adding a fixed key to the input digits position by position and keeping only the last digit of the sum (modulo 10).

This guide explains the mathematical principle behind this method and demonstrates how to implement it efficiently in Python using string manipulation and modular arithmetic.

Understanding the Logic

The algorithm processes a 4-digit number using a specific key (in this case, 9853).

The Rules:

  1. Scope: The input must be an integer between 0 and 9999.
  2. Padding: Numbers fewer than 4 digits are padded with leading zeros (e.g., 32 becomes 0032).
  3. Operation: Add the corresponding digits of the input and the key.
  4. Modulo: If the sum is ≥ 10, drop the tens digit (keep only the units digit).

Example:

  • Input: 1530
  • Key: 9853
  • Calculation:
    • 1st digit: 1 + 9 = 10 → 0
    • 2nd digit: 5 + 8 = 13 → 3
    • 3rd digit: 3 + 5 = 8 → 8
    • 4th digit: 0 + 3 = 3 → 3
  • Result: "0383"

Step 1: Input Validation and Formatting

Before processing, we must ensure the input falls within the valid range and is formatted correctly as a 4-character string.

Handling Bounds and Padding:

def prepare_input(numb: int):
# ✅ Correct: Check bounds first
if numb < 0 or numb > 9999:
return None

# ✅ Correct: Convert to string and pad with zeros
# zfill(4) adds '0' to the left until length is 4
return str(numb).zfill(4)

print(f"Padding 32: '{prepare_input(32)}'")
print(f"Padding 1530: '{prepare_input(1530)}'")
print(f"Invalid: {prepare_input(12345)}")

Output:

Padding 32:   '0032'
Padding 1530: '1530'
Invalid: None
note

Using str(numb).zfill(4) is more Pythonic than manually checking string length and prepending "0"s in a loop.

Step 2: Implementing the Encryption Loop

We need to iterate through the digits of the input and the key simultaneously. Python's zip() function is perfect for this.

The Algorithm:

def encrypt_logic(numb_str):
key_str = "9853"
result = ""

# ⛔️ Inefficient: Manual indexing
# for i in range(4):
# n = int(numb_str[i])
# k = int(key_str[i])
# ...

# ✅ Correct: Using zip() and list comprehension
# zip pairs '1' with '9', '5' with '8', etc.
chars = [str((int(n) + int(k)) % 10) for n, k in zip(numb_str, key_str)]

return "".join(chars)

# Test logic with prepared string
print(f"Encrypted '1530': {encrypt_logic('1530')}")

Output:

Encrypted '1530': 0383
warning

The modulo operator % 10 is essential. It ensures that 5 + 8 = 13 becomes 3, effectively "omitting 10" as required by the algorithm.

Complete Code Solution

Here is the robust, complete implementation handling user input, validation, and encryption in a single script.

def plain_code_encryption(numb: int) -> str:
"""
Encrypts a number (0-9999) using the Clear Code method with key 9853.
Returns None if input is out of bounds.
"""
# 1. Validation
if numb < 0 or numb > 9999:
return None

# 2. Formatting (Padding)
numb_str = str(numb).zfill(4)
key_str = "9853"

# 3. Encryption (Digit-wise addition modulo 10)
# Generator expression creates the digits on the fly
encryption_text = "".join(
str((int(n) + int(k)) % 10) for n, k in zip(numb_str, key_str)
)

return encryption_text

if __name__ == "__main__":
print("--- Test Cases ---")
print(f"Input: 1530 -> {plain_code_encryption(1530)}") # Expected: 0383
print(f"Input: 0 -> {plain_code_encryption(0)}") # Expected: 9853 (0000 + 9853)
print(f"Input: 12345 -> {plain_code_encryption(12345)}") # Expected: None

print("\n--- User Input Mode ---")
try:
user_input = int(input("Enter a number (0-9999): "))
result = plain_code_encryption(user_input)
if result:
print(f"Encrypted Code: {result}")
else:
print("Error: Number must be between 0 and 9999.")
except ValueError:
print("Error: Please enter a valid integer.")

Output:

--- Test Cases ---
Input: 1530 -> 0383
Input: 0 -> 9853
Input: 12345 -> None

--- User Input Mode ---
Enter a number (0-9999): 1530
Encrypted Code: 0383

Conclusion

The "Clear Code Encryption" method is an excellent exercise in basic cryptography logic and data manipulation.

  1. Pad your data to ensure uniform length using zfill.
  2. Iterate over parallel datasets using zip.
  3. Apply modular arithmetic (% 10) to constrain numerical results to single digits.