EXTERNAL_INS
SSL
1. openssl genpkey -algorithm RSA -out [Link] -pkeyopt rsa_keygen_bits:2048
2. openssl req -new -key [Link] -out [Link]
3. openssl req -x509 -key [Link] -in [Link] -out [Link] -days 365
4. openssl pkcs12 -export -out bundle.p12 -inkey [Link] -in [Link]
5. openssl x509 -in [Link] -text -noout
6. openssl req -in [Link] -text -noout
7. openssl s_client -connect [Link]
IDS
• sudo mkdir -p /etc/snort/rules
• sudo touch /etc/snort/rules/[Link]
• sudo nano /etc/snort/rules/[Link]
• #Paste this in that
• alert icmp any any -> any any (msg:"Ping detected"; sid:1000001;)
• sudo snort -A console -q -c /etc/snort/[Link] -i lo
• #open another terminal
• ping localhost
• #See in the first terminal it will be detected
Digital Signature
import random
def mod_exp(base, exp, mod):
return pow(base, exp, mod)
def egcd(a, b):
while b:
a, b = b, a % b
return a
def mod_inverse(k, q):
return pow(k, -1, q)
def simple_sha1(msg):
h= 0
for c in msg:
h = (h * 31 + ord(c)) % (1 << 160)
return h
p = 467
q = 233
g=2
def sign_message(message, p, q, g, x):
H = simple_sha1(message)
while True:
k = [Link](1, q - 1)
r = mod_exp(g, k, p) % q
if r == 0:
continue
try:
k_inv = mod_inverse(k, q)
except:
continue
s = (k_inv * (H + x * r)) % q
if s == 0:
continue
return (r, s)
def verify_signature(message, r, s, p, q, g, y):
if not (0 < r < q and 0 < s < q):
return False
H = simple_sha1(message)
w = mod_inverse(s, q)
u1 = (H * w) % q
u2 = (r * w) % q
v = ((mod_exp(g, u1, p) * mod_exp(y, u2, p)) % p) % q
return v == r
print("=== DSA Signature Demo ===")
print("Using toy values: p =", p, ", q =", q, ", g =", g)
while True:
try:
x = int(input(f"\nEnter private key x (1 < x < {q}): "))
if 1 < x < q:
break
else:
print("x must be in the range (1, q). Try again.")
except ValueError:
print("Invalid input. Please enter an integer.")
public_input = input(f"Enter public key y (optional, press Enter to auto-compute): ")
if public_input.strip() == "":
y = mod_exp(g, x, p)
print(f"Computed public key y = g^x mod p = {y}")
else:
try:
y = int(public_input)
except ValueError:
print("Invalid public key. Exiting.")
exit()
message = input("\nEnter message to sign: ")
r, s = sign_message(message, p, q, g, x)
print("\nGenerated Signature:")
print("r =", r)
print("s =", s)
valid = verify_signature(message, r, s, p, q, g, y)
print("\nSignature verification result:", "Valid " if valid else "Invalid ")
Diffie Hellman
import random
prime = 23 # prime number (p)
primitive_root = 5 # primitive root modulo p (g)
alice_private = [Link](1, prime - 2) # Alice's secret key
bob_private = [Link](1, prime - 2) # Bob's secret key
alice_public = pow(primitive_root, alice_private, prime)
bob_public = pow(primitive_root, bob_private, prime)
alice_shared = pow(bob_public, alice_private, prime)
bob_shared = pow(alice_public, bob_private, prime)
if alice_shared == bob_shared:
print("\nSuccess! Both share the same secret key.")
else:
print("\nError! Keys do not match.")
RSA
from math import gcd
import random
def modinv(a,m):
for x in range(1,m):
if (a*x)%m==1:
return x
def is_prime(n):
if n<2:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def generate_prime(start=100,end=300):
while True:
num=[Link](start,end)
if is_prime(num):
return num
p=generate_prime()
q=generate_prime()
n=p*q
phi=(p-1)*(q-1)
e=65537
while gcd(e,phi)!=1:
e=[Link](2,phi-1)
d=modinv(e,phi)
public_key=(e,n)
private_key=(d,n)
print("Public Key:",public_key)
print("Private Key:",private_key)
def encrypt(msg,public_key):
e,n=public_key
cipher=[pow(ord(ch),e,n) for ch in msg]
return cipher
def decrypt(msg,private_key):
d,n=private_key
plain="".join([chr(pow(ch,d,n)) for ch in msg])
return plain
msg="vihas"
cipher=encrypt(msg,public_key)
print("Encrypted Message:",cipher)
plain=decrypt(cipher,private_key)
print("Decrypted Message:",plain)
AES
def hex2bin(s):
return bin(int(s, 16))[2:].zfill(len(s)*4)
def bin2hex(s):
return hex(int(s, 2))[2:].upper().zfill(len(s)//4)
def xor(a, b):
return ''.join('0' if x == y else '1' for x, y in zip(a, b))
# Simple fixed S-box (4-bit substitution for demonstration)
sbox = {
'0000': '1110', '0001': '0100', '0010': '1101', '0011': '0001',
'0100': '0010', '0101': '1111', '0110': '1011', '0111': '1000',
'1000': '0011', '1001': '1010', '1010': '0110', '1011': '1100',
'1100': '0101', '1101': '1001', '1110': '0000', '1111': '0111'
# Inverse S-box for decryption
inv_sbox = {v: k for k, v in [Link]()}
def substitute(block, box):
result = ''
for i in range(0, len(block), 4):
nibble = block[i:i+4]
result += box[nibble]
return result
def shift_rows(block):
# Simple row shift: swap halves (8 bits each)
return block[8:] + block[:8]
def inv_shift_rows(block):
return block[8:] + block[:8]
def add_round_key(block, round_key):
return xor(block, round_key)
def simple_aes_encrypt(pt_hex, round_keys):
block = hex2bin(pt_hex)
print(f"Initial Block: {block}")
for i, rk in enumerate(round_keys):
block = substitute(block, sbox)
block = shift_rows(block)
block = add_round_key(block, rk)
print(f"Round {i+1}: {bin2hex(block)}")
return bin2hex(block)
def simple_aes_decrypt(ct_hex, round_keys):
block = hex2bin(ct_hex)
print(f"Initial Cipher Block: {block}")
for i, rk in enumerate(reversed(round_keys)):
block = add_round_key(block, rk)
block = inv_shift_rows(block)
block = substitute(block, inv_sbox)
print(f"Round {i+1}: {bin2hex(block)}")
return bin2hex(block)
# Example fixed 16-bit round keys (simple example)
round_keys = [
'0011001100110011',
'1100110011001100',
'1010101010101010',
'0101010101010101'
# Input and process
pt = input("Enter plaintext (4 hex chars): ").upper() # 16 bits = 4 hex chars
cipher_text = simple_aes_encrypt(pt, round_keys)
print("Ciphertext (hex):", cipher_text)
decrypted_text = simple_aes_decrypt(cipher_text, round_keys)
print("Decrypted Plaintext (hex):", decrypted_text)
DES
def hex2bin(s):
return bin(int(s, 16))[2:].zfill(len(s)*4)
def bin2hex(s):
return hex(int(s, 2))[2:].upper().zfill(len(s)//4)
def permute(k, arr):
return "".join(k[i-1] for i in arr)
def xor(a, b):
return ''.join('0' if x == y else '1' for x, y in zip(a, b))
# Minimal S-box: Example values (4 S-boxes, 4x4)
sbox = [
[[14,4,13,1],[2,15,11,8],[3,10,6,12],[5,9,0,7]],
[[15,1,8,14],[6,11,3,4],[9,7,2,13],[12,0,5,10]],
[[10,0,9,14],[6,3,15,5],[1,13,12,7],[11,4,2,8]],
[[7,13,14,3],[0,6,9,10],[1,2,8,5],[11,12,4,15]]
# Identity permutations (no effect)
initial_perm = list(range(1, 33))
final_perm = list(range(1, 33))
def sbox_substitute(inp):
out = ''
for i in range(4):
block = inp[i*4:(i+1)*4]
row = int(block[0] + block[3], 2)
col = int(block[1:3], 2)
val = sbox[i][row][col]
out += bin(val)[2:].zfill(4)
return out
def encrypt(pt, round_keys):
pt = hex2bin(pt)
pt = permute(pt, initial_perm)
left, right = pt[:16], pt[16:]
print(f"Initial L0: {bin2hex(left)}, R0: {bin2hex(right)}")
for i, rk in enumerate(round_keys):
xored = xor(right, rk)
sbox_out = sbox_substitute(xored[:16])
new_right = xor(left, sbox_out)
left, right = right, new_right
print(f"After round {i+1}: L{i+1}: {bin2hex(left)}, R{i+1}: {bin2hex(right)}")
combined = left + right
cipher = permute(combined, final_perm)
return cipher
def decrypt(ct, round_keys):
ct = hex2bin(ct)
ct = permute(ct, initial_perm)
left, right = ct[:16], ct[16:]
print(f"Initial L0: {bin2hex(left)}, R0: {bin2hex(right)}")
for i, rk in enumerate(reversed(round_keys)):
xored = xor(left, rk)
sbox_out = sbox_substitute(xored[:16])
new_left = xor(right, sbox_out)
right, left = left, new_left
print(f"After round {i+1}: L{i+1}: {bin2hex(left)}, R{i+1}: {bin2hex(right)}")
combined = left + right
plain_bin = permute(combined, final_perm)
return bin2hex(plain_bin)
round_keys = [bin(int('1334', 16))[2:].zfill(16)] * 16
pt = input("Enter plaintext (8 hex chars): ").upper()
ct = encrypt(pt, round_keys)
print("Ciphertext:", bin2hex(ct))
decrypted = decrypt(bin2hex(ct), round_keys)
print("Decrypted Plaintext:", decrypted)
ROW TRANSPOSITION
def row_trans_encrypt(plaintext, key, padchar='X'):
m = len(key)
if len(plaintext) % m != 0:
plaintext += padchar * (m - len(plaintext) % m)
rows = []
for i in range(0, len(plaintext), m):
[Link](list(plaintext[i:i+m]))
order = sorted(range(m), key=lambda i: (key[i], i))
ciphertext = ""
for row in rows:
for i in order:
ciphertext += row[i]
return ciphertext
def row_trans_decrypt(ciphertext, key, padchar='X'):
m = len(key)
cipher_rows = []
for i in range(0, len(ciphertext), m):
cipher_rows.append(list(ciphertext[i:i+m]))
order = sorted(range(m), key=lambda i: (key[i], i))
plaintext = ""
for crow in cipher_rows:
row = [''] * m
for idx, col in enumerate(order):
row[col] = crow[idx]
plaintext += "".join(row)
return [Link](padchar)
pt = "HELLOWORLD"
k = "4312"
ct = row_trans_encrypt(pt, k)
print("Encrypted:", ct)
print("Decrypted:", row_trans_decrypt(ct, k))
#for above iter multiple times for double columnar
HILL CIPHER
import numpy as np
def hill_encrypt(plain_text, key_matrix):
plain_text = plain_text.upper().replace(' ', '')
if len(plain_text) % 2 != 0:
plain_text += 'X'
cipher_text = ''
for i in range(0, len(plain_text), 2):
pair = [ord(plain_text[i]) - ord('A'), ord(plain_text[i+1]) - ord('A')]
result = [Link](key_matrix, pair) % 26
cipher_text += chr(result[0] + ord('A')) + chr(result[1] + ord('A'))
return cipher_text
def hill_decrypt(cipher_text, key_matrix):
det = int([Link]([Link](key_matrix))) % 26
det_inv = pow(det, -1, 26)
adjugate = [Link]([[key_matrix[1][1], -key_matrix[0][1]],
[-key_matrix[1][0], key_matrix[0][0]]]) % 26
inv_key = (det_inv * adjugate) % 26
plain_text = ''
for i in range(0, len(cipher_text), 2):
pair = [ord(cipher_text[i]) - ord('A'), ord(cipher_text[i+1]) - ord('A')]
result = [Link](inv_key, pair) % 26
plain_text += chr(int(result[0]) + ord('A')) + chr(int(result[1]) + ord('A'))
return plain_text
key_matrix = [Link]([[3, 3], [2, 5]])
plain_text = "HELLO"
cipher_text = hill_encrypt(plain_text, key_matrix)
print("Encrypted:", cipher_text)
print("Decrypted:", hill_decrypt(cipher_text, key_matrix))
RAIL FENCE
def rail_fence_encrypt(plain_text, key):
rail = [['\n' for _ in range(len(plain_text))] for _ in range(key)]
dir_down = False
row, col = 0, 0
for char in plain_text:
if row == 0 or row == key - 1:
dir_down = not dir_down
rail[row][col] = char
col += 1
row += 1 if dir_down else -1
cipher_text = ''
for i in range(key):
for j in range(len(plain_text)):
if rail[i][j] != '\n':
cipher_text += rail[i][j]
return cipher_text
def rail_fence_decrypt(cipher_text, key):
rail = [['\n' for _ in range(len(cipher_text))] for _ in range(key)]
dir_down = None
row, col = 0, 0
for _ in range(len(cipher_text)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False
rail[row][col] = '*'
col += 1
row += 1 if dir_down else -1
index = 0
for i in range(key):
for j in range(len(cipher_text)):
if rail[i][j] == '*' and index < len(cipher_text):
rail[i][j] = cipher_text[index]
index += 1
result = ''
row, col = 0, 0
for _ in range(len(cipher_text)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False
result += rail[row][col]
col += 1
row += 1 if dir_down else -1
return result
message = "HELLOTRANSPOSITION"
rail_key = 3
encrypted_rail = rail_fence_encrypt(message, rail_key)
decrypted_rail = rail_fence_decrypt(encrypted_rail, rail_key)
print(f"Rail Fence Encrypted: {encrypted_rail}")
print(f"Rail Fence Decrypted: {decrypted_rail}")
PLAY FAIR
import string
def generate_playfair_key_matrix(key):
key = "".join([Link]([Link]().replace('J', 'I')))
matrix = []
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
for char in key + alphabet:
if char not in matrix:
[Link](char)
return [matrix[i:i+5] for i in range(0, 25, 5)]
def playfair_encrypt(plain_text, key):
matrix = generate_playfair_key_matrix(key)
plain_text = plain_text.upper().replace('J', 'I').replace(' ', '')
pairs = []
i=0
while i < len(plain_text):
a = plain_text[i]
b = plain_text[i+1] if i+1 < len(plain_text) and plain_text[i+1] != a else 'X'
[Link]((a, b))
i += 2 if b != 'X' else 1
def find_position(c):
for row in range(5):
for col in range(5):
if matrix[row][col] == c:
return row, col
result = ""
for a, b in pairs:
r1, c1 = find_position(a)
r2, c2 = find_position(b)
if r1 == r2:
result += matrix[r1][(c1 + 1) % 5] + matrix[r2][(c2 + 1) % 5]
elif c1 == c2:
result += matrix[(r1 + 1) % 5][c1] + matrix[(r2 + 1) % 5][c2]
else:
result += matrix[r1][c2] + matrix[r2][c1]
return result
def playfair_decrypt(cipher_text, key):
matrix = generate_playfair_key_matrix(key)
def find_position(c):
for row in range(5):
for col in range(5):
if matrix[row][col] == c:
return row, col
result = ""
for i in range(0, len(cipher_text), 2):
a, b = cipher_text[i], cipher_text[i+1]
r1, c1 = find_position(a)
r2, c2 = find_position(b)
if r1 == r2:
result += matrix[r1][(c1 - 1) % 5] + matrix[r2][(c2 - 1) % 5]
elif c1 == c2:
result += matrix[(r1 - 1) % 5][c1] + matrix[(r2 - 1) % 5][c2]
else:
result += matrix[r1][c2] + matrix[r2][c1]
# Remove padding 'X' if it was added between identical letters or at end
cleaned_result = ""
i=0
while i < len(result):
if i + 1 < len(result) and result[i+1] == 'X' and (i+2 >= len(result) or result[i] == result[i+2]):
cleaned_result += result[i]
i += 2
else:
cleaned_result += result[i]
i += 1
return cleaned_result
# Example Usage
plain_text = "HELLO"
key = "MONARCHY"
cipher_text = playfair_encrypt(plain_text, key)
print("Encrypted:", cipher_text)
decrypted_text = playfair_decrypt(cipher_text, key)
print("Decrypted:", decrypted_text)
Caeser Cipher
def caesar_encrypt(text, shift):
result = ""
for char in text:
if [Link]():
shift_base = ord('A') if [Link]() else ord('a')
result += chr((ord(char) - shift_base + shift) % 26 + shift_base)
else:
result += char
return result
def caesar_decrypt(text, shift):
return caesar_encrypt(text, -shift)
# Example Usage
plain_text = "HELLO WORLD"
shift = 3
cipher_text = caesar_encrypt(plain_text, shift)
print("Encrypted:", cipher_text)
print("Decrypted:", caesar_decrypt(cipher_text, shift))
XOR AND ENCRYPT
input_string = input("Enter a string: ")
xor_key = 42
encrypted = ''.join(chr(ord(char) ^ xor_key) for char in input_string)
decrypted = ''.join(chr(ord(char) ^ xor_key) for char in encrypted)
print("Original string:", input_string)
print("Encrypted text:", repr(encrypted))
print("Decrypted text:", decrypted)
SHA256
K=[
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
# Initial hash values
H0 = [
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19