🔐 Public-Key Encryption Demo

Learn how asymmetric encryption works with this interactive demonstration

1

Generate Key Pair

Generate a pair of mathematically related keys. The public key can be shared openly, while the private key must remain secret. Together, they enable secure communication.

Copied!
Copied!
2

Encrypt Message

Enter a message and use one of the generated keys to encrypt it. Anyone can use your public key to encrypt messages that only you can decrypt.

🔒 Encrypted Message:
3

Decrypt Message

Use the corresponding key to decrypt the message. If you encrypted with the public key, use the private key to decrypt (and vice versa).

🔑
[DECRYPTION GUIDE]:
  • ➤ If encrypted with PUBLIC KEY: Use PRIVATE KEY to decrypt
  • ➤ If encrypted with PRIVATE KEY: Use PUBLIC KEY to decrypt
This inverse relationship between keys is fundamental to asymmetric encryption systems.
Decrypted Message:
4

Security Analysis

This demo uses a simple shift cipher for educational purposes. In real-world scenarios, such basic encryption can be broken using various tools and techniques.

👉 Click to show brute-force methods and tools
⚠️
Security Notice:
This encryption can be broken using common tools in Kali Linux:
  • CyberChef: Use the "Magic" operation to detect the encryption and try automatic decryption
  • Python script: Write a simple script to try all 256 possible shifts
  • xxd: Convert the encrypted numbers back to ASCII characters
  • Statistical analysis: Use tools like 'frequency' to analyze character distribution
Complete Python script for brute-force (save as bruteforce.py):
#!/usr/bin/env python3

import string
import sys
from typing import List, Tuple

class BruteForce:
    def __init__(self):
        # Characters that typically appear in readable text
        self.common_chars = set(string.ascii_letters + string.digits + string.punctuation + ' ')
        # Minimum percentage of readable characters to consider a result valid
        self.readability_threshold = 0.75

    def is_readable(self, text: str) -> bool:
        """Check if decrypted text appears to be readable."""
        readable_chars = sum(1 for c in text if c in self.common_chars)
        return (readable_chars / len(text)) >= self.readability_threshold

    def decrypt_with_key(self, numbers: List[int], key: int) -> str:
        """Decrypt the message using a specific key."""
        plaintext = ''
        for num in numbers:
            dec_val = num
            # Apply reverse shift key times
            for _ in range(key):
                dec_val -= 1
                if dec_val < 0:
                    dec_val = 255
            plaintext += chr(dec_val)
        return plaintext

    def find_possible_keys(self, numbers: List[int]) -> List[Tuple[int, str]]:
        """Try all possible keys and return those that produce readable text."""
        possible_solutions = []
        
        # Try all possible keys (0-255)
        for key in range(256):
            decrypted = self.decrypt_with_key(numbers, key)
            
            # If the result looks readable, add it to possible solutions
            if self.is_readable(decrypted):
                possible_solutions.append((key, decrypted))
            
        return possible_solutions

def parse_input(cipher_text: str) -> List[int]:
    """Parse the input string into a list of numbers."""
    # Remove any whitespace and split the numbers
    try:
        # Handle both space-separated and consecutive numbers
        if ' ' in cipher_text:
            return [int(x) for x in cipher_text.split()]
        else:
            # If numbers are consecutive, split every 3 digits
            return [int(cipher_text[i:i+3]) for i in range(0, len(cipher_text), 3)]
    except ValueError as e:
        print(f"Error parsing input: {e}")
        print("Input should be numbers separated by spaces or consecutive numbers")
        sys.exit(1)

def main():
    # Check if input is provided
    if len(sys.argv) < 2:
        print("Usage: python3 bruteforce.py <encrypted_numbers>")
        print("Example: python3 bruteforce.py '65 66 67'")
        print("   or: python3 bruteforce.py 656667")
        sys.exit(1)

    # Get encrypted text from command line argument
    cipher_text = sys.argv[1]
    
    # Parse the input into numbers
    numbers = parse_input(cipher_text)
    
    print(f"Attempting to decrypt: {numbers}")
    print("\nBrute-forcing all possible keys (0-255)...")
    print("-" * 50)

    # Create brute force object and find possible solutions
    brute_force = BruteForce()
    possible_solutions = brute_force.find_possible_keys(numbers)

    # Display results
    if possible_solutions:
        print(f"\nFound {len(possible_solutions)} potential solutions:")
        print("-" * 50)
        for key, decrypted in possible_solutions:
            print(f"Key {key:3d}: {decrypted}")
    else:
        print("\nNo readable solutions found!")
        print("Try adjusting the readability threshold or check the input format.")

    print("\nNote: The most likely solution is the one that makes the most sense in context.")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nBrute-force attempt cancelled by user.")
        sys.exit(0)
    except Exception as e:
        print(f"An error occurred: {e}")
        sys.exit(1)
How to use:
  1. Save the code above as bruteforce.py
  2. Make it executable: chmod +x bruteforce.py
  3. Run it with encrypted numbers either:
    • Space-separated: ./bruteforce.py "65 66 67"
    • Or consecutive: ./bruteforce.py 656667