Nighthawk Pages

Safe Computing HW

HW hack

CSP Big Idea 2

import random

def caesar_cipher(text, shift, mode):
    result = ""
    for char in text:
        if char.isalpha():  # Only encrypt/decrypt letters
            shift_amount = shift if mode == "encrypt" else -shift
            new_char = chr(((ord(char.lower()) - 97 + shift_amount) % 26) + 97)
            result += new_char.upper() if char.isupper() else new_char
        else:
            result += char  # Keep non-letter characters unchanged
    return result

# User input
mode = input("Do you want to encrypt or decrypt? ").strip().lower()
message = input("Enter your message: ")

# Accept "random" for shift
shift_input = input("Enter shift value (number of places to shift or type 'random'): ").strip().lower()
if shift_input == "random":
    shift = random.randint(1, 25)
    print(f"Random shift chosen: {shift}")
else:
    shift = int(shift_input)

# Perform encryption/decryption
output = caesar_cipher(message, shift, mode)
print(f"Result: {output}")

Result: ifmmp
Scroll to top