import re
def is_valid_ip(ip):
pattern = r'^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
return bool(re.match(pattern, ip))
# Test cases
print(is_valid_ip("192.168.1.1")) # True
print(is_valid_ip("256.256.256.256")) # False
print(is_valid_ip("1.1.1")) # False
Explanation:
def xor_encrypt_decrypt(input_string, key):
# Encrypting/Decrypting is the same operation with XOR
result = ''.join(chr(ord(char) ^ key) for char in input_string)
return result
# Test cases
key = 123 # XOR key
original_text = "Hello, World!"
encrypted_text = xor_encrypt_decrypt(original_text, key)
decrypted_text = xor_encrypt_decrypt(encrypted_text, key)
print(f"Original: {original_text}")
print(f"Encrypted: {encrypted_text}")
print(f"Decrypted: {decrypted_text}")
Explanation:
import hashlib
def hash_password(password):
# Hash the password using SHA-256
hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
return hashed_password
# Test case
password = "SecurePassword123"
hashed_password = hash_password(password)
print(f"Hashed password: {hashed_password}")
Explanation:
hashlib
library to hash a password using the SHA-256 algorithm.encode('utf-8')
method is used to convert the password to bytes, as the hashlib
functions expect byte input.
import hashlib
import os
def hash_password_with_salt(password):
# Generate a random salt
salt = os.urandom(16)
# Combine password with salt and hash using SHA-256
salted_password = password.encode('utf-8') + salt
hashed_password = hashlib.sha256(salted_password).hexdigest()
# Return both the salt and the hashed password
return salt.hex(), hashed_password
# Test case
password = "SecurePassword123"
salt, hashed_password = hash_password_with_salt(password)
print(f"Salt: {salt}")
print(f"Hashed Password: {hashed_password}")
Explanation:
os.urandom(16)
function is used to generate a 16-byte random salt.
import re
def detect_sql_injection(input_string):
# Define common SQL Injection patterns
patterns = [r"(\b(SELECT|DROP|INSERT|UPDATE|DELETE)\b)",
r"(--|\#|\*|;|/\*|\*/)",
r"(\b(OR|AND)\b\s+\d\s*=\s*\d)"]
for pattern in patterns:
if re.search(pattern, input_string, re.IGNORECASE):
return True # Potential SQL injection found
return False # No SQL injection detected
# Test cases
print(detect_sql_injection("SELECT * FROM users WHERE username = 'admin'")) # True
print(detect_sql_injection("admin' OR 1=1 --")) # True
print(detect_sql_injection("user input")) # False
Explanation:
SELECT
, DROP
, OR 1=1
), SQL comment syntax (--
, #
, etc.), and suspicious logical statements that could indicate an SQL injection attempt.
def caesar_cipher(text, shift, mode='encrypt'):
result = ""
# Shift the text based on the operation mode
if mode == 'decrypt':
shift = -shift
for char in text:
if char.isalpha(): # Only shift alphabetic characters
shift_base = 65 if char.isupper() else 97
result += chr((ord(char) - shift_base + shift) % 26 + shift_base)
else:
result += char # Non-alphabetic characters remain unchanged
return result
# Test cases
original_text = "Hello, World!"
shift = 3
encrypted_text = caesar_cipher(original_text, shift, mode='encrypt')
decrypted_text = caesar_cipher(encrypted_text, shift, mode='decrypt')
print(f"Original: {original_text}")
print(f"Encrypted: {encrypted_text}")
print(f"Decrypted: {decrypted_text}")
Explanation:
import secrets
# A mock function to generate and store a CSRF token in a session
def generate_csrf_token():
return secrets.token_hex(16)
# Function to check if the CSRF token in the request matches the stored token
def check_csrf_token(request_token, session_token):
if request_token == session_token:
return True # CSRF token is valid
return False # CSRF token is invalid
# Example usage
session_token = generate_csrf_token() # Simulate storing a CSRF token in a session
request_token = session_token # Simulate a valid CSRF token in the request
is_valid = check_csrf_token(request_token, session_token)
print(f"CSRF Token is valid: {is_valid}")
Explanation:
secrets
for generating secure random tokens ensures that the CSRF token is unpredictable.
def brute_force_crack(password, dictionary):
for word in dictionary:
if word == password:
return f"Password cracked: {word}"
return "Password not found in dictionary"
# Test case
password = "admin123"
dictionary = ["password", "123456", "admin123", "qwerty"]
result = brute_force_crack(password, dictionary)
print(result)
Explanation:
import re
def is_strong_password(password):
if len(password) < 8:
return False
if not re.search(r"[a-z]", password):
return False
if not re.search(r"[A-Z]", password):
return False
if not re.search(r"[0-9]", password):
return False
if not re.search(r"[\W_]", password): # Non-word characters (special characters)
return False
return True
# Test cases
print(is_strong_password("Password123!")) # True
print(is_strong_password("weakpassword")) # False
print(is_strong_password("12345")) # False
Explanation:
import re
def detect_xss(input_string):
xss_patterns = [
r"<script.*?>.*?</script>", # Matches <script> tags
r"javascript:.*", # Matches JavaScript pseudo-protocol
r"on\w+\s*=", # Matches event handlers (e.g., onclick=, onload=)
]
for pattern in xss_patterns:
if re.search(pattern, input_string, re.IGNORECASE):
return True # Potential XSS attack detected
return False # No XSS detected
# Test cases
print(detect_xss("<script>alert('XSS');</script>")) # True
print(detect_xss("Hello, World!")) # False
print(detect_xss('<a href="javascript:alert(1)">Click me</a>')) # True
Explanation:
<script>
tags and JavaScript event handlers (onclick
, onload
, etc.).True
if any suspicious pattern is detected.
import base64
def base64_encode(input_string):
encoded_bytes = base64.b64encode(input_string.encode('utf-8'))
return encoded_bytes.decode('utf-8')
def base64_decode(encoded_string):
decoded_bytes = base64.b64decode(encoded_string)
return decoded_bytes.decode('utf-8')
# Test cases
encoded = base64_encode("Hello, World!")
print(f"Encoded: {encoded}")
decoded = base64_decode(encoded)
print(f"Decoded: {decoded}")
Explanation:
base64.b64encode
and base64.b64decode
are used to handle the encoding and decoding process in Python.
import ssl
import socket
def check_ssl_configuration(hostname, port=443):
context = ssl.create_default_context()
try:
# Connect to the server and wrap the connection in SSL
connection = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=hostname)
connection.connect((hostname, port))
# Get the SSL certificate
ssl_info = connection.getpeercert()
# Check if the SSL/TLS version and cipher suite are considered weak
cipher_suite = connection.cipher()
if cipher_suite:
cipher_name = cipher_suite[0]
if 'RC4' in cipher_name or '3DES' in cipher_name:
return f"Warning: Weak cipher suite detected: {cipher_name}"
else:
return f"SSL/TLS connection is secure with cipher suite: {cipher_name}"
else:
return "Unable to determine the cipher suite."
except Exception as e:
return f"SSL/TLS check failed: {e}"
# Test case
hostname = "www.google.com"
print(check_ssl_configuration(hostname))
Explanation:
ssl
and socket
libraries to establish an SSL/TLS connection with the server and retrieve information about the SSL configuration.