Certainly! Here's an example of a Python script for a simple cybersecurity Capture the Flag (CTF) challenge:
import random
import string
import hashlib
def generate_flag():
# Generate a random flag
flag_length = 20
flag_chars = string.ascii_letters + string.digits
flag = ''.join(random.choice(flag_chars) for _ in range(flag_length))
return flag
def encrypt_flag(flag):
# Encrypt the flag using a simple XOR cipher
key = 'secret_key'
encrypted_flag = ''.join(chr(ord(c) ^ ord(k)) for c, k in zip(flag, key * (len(flag) // len(key) + 1)))
return encrypted_flag
def hash_password(password):
# Hash the password using SHA-256
hashed_password = hashlib.sha256(password.encode()).hexdigest()
return hashed_password
def main():
print("Welcome to the CTF challenge!")
# Generate and encrypt the flag
flag = generate_flag()
encrypted_flag = encrypt_flag(flag)
print("Encrypted flag:", encrypted_flag)
# Prompt the user for the password
password = input("Enter the password to decrypt the flag: ")
# Hash the user's password
hashed_password = hash_password(password)
# Check if the hashed password matches the expected value
expected_hash = "f7c3bc1d808e04732adf679965ccc34ca7ae3441123bc683d3621f2e0e37e106"
if hashed_password == expected_hash:
# Decrypt and display the flag
decrypted_flag = encrypt_flag(encrypted_flag)
print("Congratulations! You have captured the flag:", decrypted_flag)
else:
print("Incorrect password. Try again.")
if __name__ == '__main__':
main()
In this example, the script generates a random flag using a combination of ASCII letters and digits. The flag is then encrypted using a simple XOR cipher with a secret key. The encrypted flag is displayed to the user.
The user is prompted to enter a password to decrypt the flag. The entered password is hashed using the SHA-256 algorithm and compared against an expected hash value. If the hashed password matches the expected value, the encrypted flag is decrypted using the same XOR cipher and displayed to the user. Otherwise, an incorrect password message is shown.
To solve this CTF challenge, participants would need to analyze the script, understand the encryption and hashing mechanisms used, and determine the correct password that produces the expected hash value. They can then enter the correct password to decrypt and capture the flag.
Note: This is a simplified example for demonstration purposes. In real CTF challenges, the encryption and hashing mechanisms may be more complex, and additional challenges or obfuscation techniques can be incorporated to increase the difficulty level.