Crypto Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

SAGE University

Indore

Institute of Advance computing


Lab Manual File

Academic Year: - 2023-2024


Semester: Fourth
Name of Student: Omkar Datey EnrollmentNo: 22ADV3CSF0011

Subject Name : Cryptography using Python

Subject Code : ACTDECWP005T/P


Lab Manual: Cryptography using Python
Topic:- Asymetric Encryption
Objectives:
1. Understand the principles of asymmetric encryption.
2. Learn how to generate public and private keys.
3. Encrypt and decrypt messages using RSA.

Prerequisites:
 Python 3.x installed on your computer.
 cryptography library installed. Install using pip install cryptography.

Lab Setup:
1. Install Required Libraries:
pip install pycryptodome

Sections:
1. Introduction to Asymmetric Encryption
2. Key Generation
3. Encryption
4. Decryption

1. Introduction to Asymmetric Encryption


Asymmetric encryption uses two different keys for encryption and decryption.
The public key is used for encryption, and the private key is used for decryption.
RSA (Rivest-Shamir-Adleman) is one of the most widely used asymmetric
encryption algorithms.
2. Key Generation
To perform RSA encryption, you first need to generate a pair of keys: one public
and one private.

from Crypto.PublicKey import RSA

# Generate RSA key pair

key = RSA.generate(2048)

private_key = key.export_key()

public_key = key.publickey().export_key()

# Save the keys to files

with open('private.pem', 'wb') as priv_file:

priv_file.write(private_key)

with open('public.pem', 'wb') as pub_file:

pub_file.write(public_key)

print("Keys generated and saved to files.")


Output:-
Public Key

Private Key
3. Encryption
Using the public key, you can encrypt a message.

from Crypto.PublicKey import RSA

from Crypto.Cipher import PKCS1_OAEP

from base64 import b64encode

# Load public key

with open('public.pem', 'rb') as pub_file:

public_key = RSA.import_key(pub_file.read())

# Message to be encrypted

message = "This is a secret message."

# Encrypt the message

cipher_rsa = PKCS1_OAEP.new(public_key)

encrypted_message = cipher_rsa.encrypt(message.encode())

# Encode the encrypted message in base64 for readability

encrypted_message_base64 = b64encode(encrypted_message)

print("Encrypted message:", encrypted_message_base64.decode())

Output
4. Decryption
Using the private key, you can decrypt the ciphertext back to the original message.

from Crypto.PublicKey import RSA

from Crypto.Cipher import PKCS1_OAEP

from base64 import b64decode

# Function to add padding to base64 string

def add_padding(base64_string):

return base64_string + '=' * (-len(base64_string) % 4)

# Load private key

with open('private.pem', 'rb') as priv_file:

private_key = RSA.import_key(priv_file.read())

# Encrypted message (base64 encoded)

encrypted_message_base64 = "<place your base64 encoded encrypted message here>"

encrypted_message_base64 = add_padding(encrypted_message_base64) # Add padding if


necessary

encrypted_message = b64decode(encrypted_message_base64)

# Decrypt the message

cipher_rsa = PKCS1_OAEP.new(private_key)

decrypted_message = cipher_rsa.decrypt(encrypted_message)

print("Decrypted message:", decrypted_message.decode())


Output

Project 01
Topic:- Login Page which stores password as Hash in
database match it fir login access

(HTML and CSS):-


By Using some images and animation in css following is the login page and
signup page is created also we are using XAMPP server for testing and
database :-
Signup page:-

After Login Access redirected to a Welcome page:-


Practice Question:-
# 1. Write a Python code to print all available hashing algorithms?

import hashlib

print(hashlib.algorithms_available)

$OUTPUT-

# 2. Write a Python code to create a word dictionary using the


alphabet 'a', 'b', 'c', 'd' with a length of 5?

import itertools

# Define the alphabet and word length


alphabet = 'abcd'
word_length = 5

# Use itertools.product to generate all combinations


combinations = itertools.product(alphabet, repeat=word_length)

# Create the word dictionary


word_dict = {''.join(combination): None for combination in
combinations}

# Optionally, if you need the dictionary to hold some values, you can
initialize it differently, e.g., with a count or some default value
# word_dict = {''.join(combination): 0 for combination in
combinations}

# Print the number of words in the dictionary to verify


print(f"Number of words in the dictionary: {len(word_dict)}")

# Print the first 10 words as a sample


for i, word in enumerate(word_dict):
if i < 10:
print(word)
else:
break

$OUTPUT-

# 3. Write a program to convert the string 'MD5 HASH' to a hash using


the md5 hashing algorithm?

import hashlib

print(hashlib.md5(b'Hello World').hexdigest())

$OUTPUT-

# 4. Write a program to store the hash and salt using the PBKDF2_HMAC
algorithm?

import hashlib
import os
import base64

def generate_salt(length=16):
"""Generate a random salt."""
return os.urandom(length)

def hash_password(password, salt, iterations=100000,


hash_name='sha256'):
"""Hash a password with the given salt using PBKDF2_HMAC."""
password_bytes = password.encode('utf-8') # Convert the password
to bytes
dk = hashlib.pbkdf2_hmac(hash_name, password_bytes, salt,
iterations)
return dk

def store_password(password, iterations=100000, hash_name='sha256'):


"""Generate salt and hash the password, then store them."""
salt = generate_salt()
hash_bytes = hash_password(password, salt, iterations, hash_name)

# Encode salt and hash for storage (e.g., in a database)


salt_b64 = base64.b64encode(salt).decode('utf-8')
hash_b64 = base64.b64encode(hash_bytes).decode('utf-8')

return salt_b64, hash_b64

def verify_password(stored_password, provided_password, stored_salt,


iterations=100000, hash_name='sha256'):
"""Verify a provided password against the stored hash and salt."""
salt = base64.b64decode(stored_salt.encode('utf-8'))
stored_hash = base64.b64decode(stored_password.encode('utf-8'))

provided_hash = hash_password(provided_password, salt, iterations,


hash_name)

return provided_hash == stored_hash

# Example usage:
password = "secure_password"

# Store the password


salt_b64, hash_b64 = store_password(password)
print("Salt (base64):", salt_b64)
print("Hash (base64):", hash_b64)
# Verify the password
is_valid = verify_password(hash_b64, password, salt_b64)
print("Password is valid:", is_valid)

# Verify with the wrong password


is_valid = verify_password(hash_b64, "wrong_password", salt_b64)
print("Password is valid:", is_valid)

$OUTPUT-

# 5. Write a program to convert the string 'sha hash' to a hash using


the sha256 hashing algorithm?

import hashlib

print(hashlib.sha256(b'Hello World').hexdigest())

$OUTPUT-

# 6. Write a program to convert the string 'cryptography' to a hash


using the SHA-512 hashing algorithm?

import hashlib

print(hashlib.sha512(b'cryptography').hexdigest())

$OUTPUT-
# 7. Write a program to convert the string 'hello world' to a hash
using the sha3_512 hashing algorithm

import hashlib

print(hashlib.sha3_512(b'hello World').hexdigest())

$OUTPUT-

# 8. Write a program to convert the string 'black2b hash' to a hash


using the blake2b hashing algorithm?

import hashlib

print(hashlib.blake2b(b'black2b hash').hexdigest())

$OUTPUT-

# 9. write a program for Add a User & password with pbkdf2_hmac?

import hashlib
import os
import base64
import json

def generate_salt(length=16):
"""Generate a random salt."""
return os.urandom(length)

def hash_password(password, salt, iterations=100000,


hash_name='sha256'):
"""Hash a password with the given salt using PBKDF2_HMAC."""
password_bytes = password.encode('utf-8') # Convert the password
to bytes
dk = hashlib.pbkdf2_hmac(hash_name, password_bytes, salt,
iterations)
return dk

def add_user(username, password, user_db, iterations=100000,


hash_name='sha256'):
"""Add a new user with a hashed password to the user database."""
salt = generate_salt()
hash_bytes = hash_password(password, salt, iterations, hash_name)

# Encode salt and hash for storage


salt_b64 = base64.b64encode(salt).decode('utf-8')
hash_b64 = base64.b64encode(hash_bytes).decode('utf-8')

# Store the username, salt, and hash in the database


user_db[username] = {
'salt': salt_b64,
'hash': hash_b64,
'iterations': iterations,
'hash_name': hash_name
}

def save_user_db(user_db, filename='user_db.json'):


"""Save the user database to a file."""
with open(filename, 'w') as f:
json.dump(user_db, f)

def load_user_db(filename='user_db.json'):
"""Load the user database from a file."""
try:
with open(filename, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {}

def main():
user_db = load_user_db()

print("Add a new user")


username = input("Enter username: ")
password = input("Enter password: ")

add_user(username, password, user_db)


save_user_db(user_db)

print(f"User '{username}' added successfully!")

if __name__ == "__main__":
main()

$OUTPUT-

# 10. write a python code on shift variable?

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
in_string = input("Enter message, Hint HELLO: ")
shift = int(input("Enter a shift number :"))
n = len(in_string)
out_string = ""
for i in range(n):
c = in_string[i]
loc = alpha.find(c.upper())
new_loc = loc + shift
if new_loc >= 26:
new_loc -= 26
out_string += alpha[new_loc]
print (i, c, loc, new_loc, out_string)
print ("Output After Encryption :", out_string)

$OUTPUT-

# 11. Write a Python code to print all available hashing Algorithm


Guaranteed?

import hashlib

print(hashlib.algorithms_guaranteed)

$OUTPUT-

# 12. Write a program to convert the string '128 hashing' to a hash


using the shake_128 hashing algorithm?

import hashlib
print(hashlib.shake_128(b'128 hashing').hexdigest(20))

$OUTPUT-
# 13. Write a program for password verification attempt with
(incorrect password or correct password) using any hashing algorithm?

import hashlib
import os
import base64
import json

def generate_salt(length=16):
"""Generate a random salt."""
return os.urandom(length)

def hash_password(password, salt, iterations=100000,


hash_name='sha256'):
"""Hash a password with the given salt using PBKDF2_HMAC."""
password_bytes = password.encode('utf-8') # Convert the password
to bytes
dk = hashlib.pbkdf2_hmac(hash_name, password_bytes, salt,
iterations)
return dk

def add_user(username, password, user_db, iterations=100000,


hash_name='sha256'):
"""Add a new user with a hashed password to the user database."""
salt = generate_salt()
hash_bytes = hash_password(password, salt, iterations, hash_name)

# Encode salt and hash for storage


salt_b64 = base64.b64encode(salt).decode('utf-8')
hash_b64 = base64.b64encode(hash_bytes).decode('utf-8')

# Store the username, salt, and hash in the database


user_db[username] = {
'salt': salt_b64,
'hash': hash_b64,
'iterations': iterations,
'hash_name': hash_name
}

def verify_password(stored_password, provided_password, stored_salt,


iterations=100000, hash_name='sha256'):
"""Verify a provided password against the stored hash and salt."""
salt = base64.b64decode(stored_salt.encode('utf-8'))
stored_hash = base64.b64decode(stored_password.encode('utf-8'))

provided_hash = hash_password(provided_password, salt, iterations,


hash_name)

return provided_hash == stored_hash

def save_user_db(user_db, filename='user_db.json'):


"""Save the user database to a file."""
with open(filename, 'w') as f:
json.dump(user_db, f)

def load_user_db(filename='user_db.json'):
"""Load the user database from a file."""
try:
with open(filename, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {}

def main():
user_db = load_user_db()

while True:
action = input("Do you want to add a user (add) or verify a
password (verify)? ").strip().lower()

if action == 'add':
username = input("Enter username: ").strip()
password = input("Enter password: ").strip()
add_user(username, password, user_db)
save_user_db(user_db)
print(f"User '{username}' added successfully!")

elif action == 'verify':


username = input("Enter username: ").strip()
password = input("Enter password: ").strip()

if username in user_db:
stored_data = user_db[username]
is_valid = verify_password(
stored_data['hash'], password,
stored_data['salt'],
stored_data['iterations'],
stored_data['hash_name']
)
if is_valid:
print("Password is correct!")
else:
print("Password is incorrect!")
else:
print("Username not found.")

else:
print("Invalid action. Please enter 'add' or 'verify'.")

if __name__ == "__main__":
main()

$OUTPUT-

# 14. Write a program to convert the string 'crypto world' to a hash


using the sha3_224 hashing algorithm?
import hashlib
print(hashlib.sha3_224(b'crypto world').hexdigest())

$OUTPUT-

# 15. Write a program to convert the string 'crypto' to a hash using


the sha3_384 hashing algorithm ?

import hashlib
print(hashlib.sha3_384(b'crypto').hexdigest())

$OUTPUT-

# 16. Write a program to convert the string 'sha1 hash' to a hash


using the sha1 hashing algorithm ?

import hashlib
print(hashlib.sha1(b'sha1 hash').hexdigest())

$OUTPUT-

#17 Write a Python code to encrypt 'test.jpeg' using AES encryption ?

import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms,
modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding as
asym_padding

# Generate a random key and IV


def generate_key_iv(password, salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
key = kdf.derive(password)
iv = os.urandom(16)
return key, iv

# Encrypt the file


def encrypt_file(input_file, output_file, key, iv):
cipher = Cipher(algorithms.AES(key), modes.CBC(iv),
backend=default_backend())
encryptor = cipher.encryptor()
padder = padding.PKCS7(algorithms.AES.block_size).padder()

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


file_data = f.read()

padded_data = padder.update(file_data) + padder.finalize()


encrypted_data = encryptor.update(padded_data) +
encryptor.finalize()

with open(output_file, 'wb') as f:


f.write(iv + encrypted_data) # Prepend IV for use in
decryption
def main():
password = b'my_strong_password'
salt = os.urandom(16) # You should save this salt to use during
decryption
key, iv = generate_key_iv(password, salt)

input_file = 'test.jpeg'
output_file = 'test_encrypted.jpeg'
encrypt_file(input_file, output_file, key, iv)

print(f"File '{input_file}' has been encrypted and saved as


'{output_file}'.")

if __name__ == "__main__":
main()

# 18. Write a program to convert the string 'crypto world' to a hash


using the sha3_256 hashing algorithm ?

import hashlib
print(hashlib.sha3_256(b'crypto world').hexdigest())

$OUTPUT-

# 20. Write a program to convert the string 'cryptography' to a hash


using the shake_256 hashing algorithm ?

import hashlib

print(hashlib.shake_256(b'cryptography').hexdigest(20))
$OUTPUT-

# 22. Write a program to convert the string 'cryptography' to a hash


using the shake_256 hashing algorithm ?

import hashlib

print(hashlib.shake_256(b'cryptography').hexdigest(20))

$OUTPUT-

You might also like