0% found this document useful (0 votes)
22 views10 pages

INSPRAC

Uploaded by

mrkrish057
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

INSPRAC

Uploaded by

mrkrish057
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1A) Caesar cipher substitution sipher

def caesar_cipher(text, shift=3, decrypt=False):

if decrypt:

shift = -shift

upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

lower_case = 'abcdefghijklmnopqrstuvwxyz'

trans_upper = upper_case[shift % 26:] + upper_case[:shift % 26]

trans_lower = lower_case[shift % 26:] + lower_case[:shift % 26]

table = str.maketrans(upper_case + lower_case, trans_upper + trans_lower)

return text.translate(table)

if __name__ == "__main__":

plaintext = input("Enter plaintext: ")

encrypted = caesar_cipher(plaintext)

print("Encrypted Message:", encrypted)

decrypted = caesar_cipher(encrypted, decrypt=True)

print("Decrypted Message:", decrypted)

print("YOUR NAME")

1B. Caesar cipher substitution cipher with user input shift


def caesar_cipher(text, shift=3, decrypt=False):

if decrypt:

shift = -shift

upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

lower_case = 'abcdefghijklmnopqrstuvwxyz'

trans_upper = upper_case[shift % 26:] + upper_case[:shift % 26]

trans_lower = lower_case[shift % 26:] + lower_case[:shift % 26]

table = str.maketrans(upper_case + lower_case, trans_upper + trans_lower)

return text.translate(table)

if __name__ == "__main__":

plaintext = input("Enter plaintext: ")

shift = int(input("Enter shift value: "))

encrypted = caesar_cipher(plaintext, shift)


print("Encrypted Message:", encrypted)

decrypted = caesar_cipher(encrypted, shift, decrypt=True)

print("Decrypted Message:", decrypted)

print("YOUR NAME")

1C Rail fence transposition cipher


def railfence_encrypt(text, key):

rail = [''] * key

row, step = 0, 1

for char in text:

rail[row] += char

row += step

if row == 0 or row == key - 1: step = -step

return ''.join(rail)

def railfence_decrypt(cipher, key):

rail = [[''] * len(cipher) for _ in range(key)]

idx, row, step = 0, 0, 1

for i in range(len(cipher)):

rail[row][i] = '*'

row += step

if row == 0 or row == key - 1: step = -step

for r in range(key):

for c in range(len(cipher)):

if rail[r][c] == '*': rail[r][c] = cipher[idx]; idx += 1

result, row, step = [], 0, 1

for i in range(len(cipher)):

result.append(rail[row][i])

row += step

if row == 0 or row == key - 1: step = -step

return ''.join(result)
message = "HELLOWORLD"

key = 2

print(f"Encrypted Message: {railfence_encrypt(message, key)}")

print(f"Decrypted Message: {railfence_decrypt(railfence_encrypt(message, key), key)}")

print("YOUR NAME")

1D. Columnar transposition cipher


import math

def columnar_encrypt(text, key):

cols, rows = len(key), math.ceil(len(text) / len(key))

grid = ['' for _ in range(cols)]

for i, char in enumerate(text):

grid[i % cols] += char

sorted_key_indices = sorted(range(cols), key=lambda x: key[x])

return ''.join(grid[i] for i in sorted_key_indices)

def columnar_decrypt(cipher_text, key):

cols = len(key)

sorted_key_indices = sorted(range(cols), key=lambda x: key[x])

grid = ['' for _ in range(cols)]

index = 0

for i in sorted_key_indices:

grid[i] = cipher_text[index:index + math.ceil(len(cipher_text) / cols)]

index += math.ceil(len(cipher_text) / cols)

return ''.join(''.join(grid[j][i] for j in range(cols) if i < len(grid[j])) for i in


range(math.ceil(len(cipher_text) / cols)))

if __name__ == "__main__":

plain_text = input("Enter plain text: ")

key = input("Enter key (numeric, e.g., 1234): ")


encrypted = columnar_encrypt(plain_text, key)

print("Encrypted text:", encrypted)

decrypted = columnar_decrypt(encrypted, key)

print("Decrypted text:", decrypted)

print("YOUR NAME")

2 Diffie helman
def power(a, b, p):

return pow(a, b, p)

def main():

P, G = 23, 10

a, b = 4, 3

x, y = power(G, a, P), power(G, b, P)

ka, kb = power(y, a, P), power(x, b, P)

print(f"P: {P}, G: {G}, Private keys: a={a}, b={b}")

print(f"Secret key for Party 1: {ka}, Secret key for Party 2: {kb}")

if __name__ == "__main__":

main()

print("YOUR NAME")

3.DES
from Crypto.Cipher import DES

import os

def des_encrypt_decrypt(text, key):

cipher = DES.new(key, DES.MODE_CBC)

iv = cipher.iv

encrypted = cipher.encrypt(text.ljust(16).encode())

decrypted = DES.new(key, DES.MODE_CBC, iv).decrypt(encrypted).strip().decode()


return encrypted, decrypted

if __name__ == "__main__":

key = os.urandom(8)

plaintext = input("Enter text: ")

encrypted, decrypted = des_encrypt_decrypt(plaintext, key)

print("Encrypted:", encrypted.hex())

print("Decrypted:", decrypted)

print("YOUR NAME")

4.RSA
import random

import random

def gcd(a, b):

while b: a, b = b, a % b

return a

def mod_inverse(e, phi):

for d in range(1, phi):

if (e * d) % phi == 1: return d

def generate_keypair(p, q):

n=p*q

phi = (p - 1) * (q - 1)

e = random.randrange(1, phi)

while gcd(e, phi) != 1: e = random.randrange(1, phi)

return (e, n), (mod_inverse(e, phi), n)

def encrypt(public_key, plaintext):

e, n = public_key
return [pow(ord(c), e, n) for c in plaintext]

def decrypt(private_key, ciphertext):

d, n = private_key

return ''.join(chr(pow(c, d, n)) for c in ciphertext)

if __name__ == "__main__":

p, q = 61, 53

public_key, private_key = generate_keypair(p, q)

print("Public Key:", public_key)

print("Private Key:", private_key)

plaintext = input("Enter plaintext: ")

encrypted = encrypt(public_key, plaintext)

print("Encrypted:", encrypted)

decrypted = decrypt(private_key, encrypted)

print("Decrypted:", decrypted)

print("YOUR NAME")

5.MESSAGE DIGEST 5
from cryptography.hazmat.primitives.asymmetric import dsa

from cryptography.hazmat.primitives import hashes

from cryptography.hazmat.backends import default_backend

msg = input("Enter message: ").strip()

if not msg:

print("Error: Message cannot be empty.")

else:

priv_key = dsa.generate_private_key(2048, default_backend())

sig = priv_key.sign(msg.encode(), hashes.SHA256())


print(f"Signature: {sig.hex()}")

print(f"Valid: {priv_key.public_key().verify(sig, msg.encode(), hashes.SHA256()) is None}")

print("YOUR NAME")

6.DIGITAL SIGNATURE

from cryptography.hazmat.primitives.asymmetric import dsa

from cryptography.hazmat.primitives import hashes

from cryptography.hazmat.backends import default_backend

msg = input("Enter message: ").strip()

if not msg:

print("Error: Message cannot be empty.")

else:

priv_key = dsa.generate_private_key(2048, default_backend())

sig = priv_key.sign(msg.encode(), hashes.SHA256())

print(f"Signature: {sig.hex()}")

print(f"Valid: {priv_key.public_key().verify(sig, msg.encode(), hashes.SHA256()) is None}")

print("YOUR NAME")

7.MAC

from cryptography.hazmat.primitives import hashes

from cryptography.hazmat.primitives.hmac import HMAC

from cryptography.hazmat.backends import default_backend

import os

def generate_key():

return os.urandom(32) # 256-bit key


def compute_hmac(key, message):

hmac = HMAC(key, hashes.SHA256(), backend=default_backend())

hmac.update(message.encode())

return hmac.finalize()

if __name__ == "__main__":

print("-MAC-")

key = generate_key()

print(f"Secret Key: {key.hex()}")

message = input("Enter message: ").strip()

if not message:

print("Error: Message cannot be empty.")

else:

hmac = compute_hmac(key, message)

print(f"HMAC: {hmac.hex()}")

hmac_to_verify = bytes.fromhex(input("Enter HMAC to verify: ").strip())

# Create a new HMAC context for verification

try:

hmac_verifier = HMAC(key, hashes.SHA256(), backend=default_backend())

hmac_verifier.update(message.encode())

hmac_verifier.verify(hmac_to_verify)

print("HMAC is valid.")

except Exception:

print("HMAC is invalid.")

print("YOUR NAME")
8.MALWARE
import hashlib

import os

KNOWN_MALWARE_HASHES = {

'e99a18c428cb38d5f260853678922e03',

'5e884898da28047151d0e56f8dc62927'

def compute_file_hash(file_path, hash_algo='md5'):

"""Compute the hash of a file."""

hash_func = hashlib.new(hash_algo)

with open(file_path, 'rb') as f:

for chunk in iter(lambda: f.read(8192), b''):

hash_func.update(chunk)

return hash_func.hexdigest()

def scan_file(file_path):

"""Scan a file for known malware hashes."""

file_hash = compute_file_hash(file_path)

if file_hash in KNOWN_MALWARE_HASHES:

print(f"Malware detected: {file_path}")

return True

print(f"File is clean: {file_path}")

return False

def scan_directory(directory):

"""Scan all files in a directory."""

for root, _, files in os.walk(directory):

for file in files:

scan_file(os.path.join(root, file))

def main():

directory = input("Enter the directory to scan: ").strip()

if not os.path.isdir(directory):

print("Invalid directory.")
return

print("Scanning directory for malware...")

scan_directory(directory)

print("Scan completed.")

if __name__ == "__main__":

print("\t-Malware Antivirus-")

main()

print("your name")

You might also like