CIS
CIS Journal Index
Practical- 01
AIM : Write a program to store username and password in an encrypted form in a database to
implement integrity lock. (MD5 and SHA-256 Algorithm)
Sql command:
mysql> SHOW DATABASES;
mysql> CREATE DATABASE credentials;
mysql> USE credentials;
mysql> CREATE TABLE usercredentials (
uid INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(255) DEFAULT NULL,
userpassword VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (uid),
UNIQUE KEY username (username)
);
Using MD5
Insert DATA:
mysql> INSERT INTO usercredentials (username, userpassword)
VALUES ('hs1.S', MD5('harikesh1234'));
mysql> SELECT * FROM usercredentials WHERE username = 'Harikesh.S';
mysql> SELECT * FROM usercredentials;
mysql> INSERT INTO usercredentials (username, userpassword)
VALUES ('hs1.S', SHA2('Harikesh1234', 256));
Output:
Conclusion:- Hence ,Successfully completed database commands using MD5 and SHA 256 for Encryption of User’s passwords
Practical- 02
AIM : Write a program to Demonstrate how to encrypt and decrypt the contents of an XML node
using 128-bit CBC AES Encryption.
Code:
Msg.xml
Code-
<?xml version="1.0"?>
<data>
<user name="user1">
<msg>user1: This is the secret text to encrypt by user1</msg>
</user>
<user name="user2">
<msg>user2: This is the secret text to encrypt by user2</msg>
</user>
<user name="user3">
<msg>user3: This is the secret text to encrypt by user3</msg>
</user>
</data>
Code:
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto import Random
import xml.etree.ElementTree as ET
# AES CBC mode is used for encryption
def encrypt(plain_text, key):
cipher = AES.new(key, AES.MODE_CBC)
b = pad(plain_text.encode("UTF-8", "ignore"), AES.block_size)
return base64.b64encode(cipher.iv + cipher.encrypt(b))
def decrypt(enc_text, key):
enc_text = base64.b64decode(enc_text)
iv = enc_text[:AES.block_size]
enc_text = enc_text[AES.block_size:]
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
b = unpad(cipher.decrypt(enc_text), AES.block_size)
return b.decode("UTF-8", "ignore")
# Secret key for encryption - must be 16 bytes for AES-128
key = Random.get_random_bytes(16)
plain_text = "This is the secret text to encrypt"
print("Key: ", base64.b64encode(key))
print("plain_text: ", plain_text)
try:
# Encrypt the msg tag
tree = ET.parse('msg.xml')
root = tree.getroot()
for msg in root.iter('msg'):
enc_msg = encrypt(msg.text, key)
msg.text = enc_msg.decode("utf-8")
msg.set('encryption', 'AES-128 CBC')
tree.write('encrypted_msg.xml', encoding='utf-8', xml_declaration=True)
print("Encrypted messages stored in encrypted_msg.xml file")
# Decrypt the msg tag
tree = ET.parse('encrypted_msg.xml')
root = tree.getroot()
for msg in root.iter('msg'):
dec_msg = decrypt(msg.text, key)
msg.text = dec_msg
tree.write('decrypted_msg.xml', encoding='utf-8', xml_declaration=True)
print("Decrypted messages stored in decrypted_msg.xml file")
except (ValueError, KeyError):
print("Error occurred")
Output:
Conclusion:- Hence, We have successfully completed the above in encrypt and decrypt the contents of an XML node using 128-bit CBC AES Encryption
Practical- 03
AIM : Write a Program to Implement Multilevel Security. (viewing and writing)
Code:
import os
security_levels = {
'top secret': 3,
'secret': 2,
'confidential': 1,
'unclassified': 0
}
print("Enter your security clearance level:")
for clearance in security_levels.keys():
print(f"- {clearance}")
user_clearance = input("> ").lower()
if user_clearance not in security_levels.keys():
print("Invalid security clearance level.")
exit()
filename = "demo.txt"
with open(filename, "r") as f:
content = f.read()
file_clearance = security_levels['secret']
if security_levels[user_clearance] >= file_clearance:
print("Access granted.")
print(content)
else:
print("Access denied.")
Output:
Conclusion:-
Hence we have successfully Implemented Multilevel Security. (viewing and writing)with have secret key
Practical No. 04
Aim: Write a program to send an encrypted email
Code:
import smtplib
from cryptography.fernet import Fernet
# SMTP server details
smtp_server = 'smtp.gmail.com'
smtp_port = 587
# Your email
smtp_username = 'sewestiangamer@gmail.com'
smtp_password = 'moxk gpge jpng wolj'
# Email details
sender = 'sewestiangamer@gmail.com'
recipient = 'harikesh8530@gmail.com'
subject = 'Testing Encrypted Email'
message = 'Hello World! This is a test email by harikesh.'
# Generate encryption key
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt the message
encrypted_message = cipher.encrypt(message.encode('utf-8'))
# Create encrypted email
msg = f"""From: {sender}
To: {recipient}
Subject: {subject}
Encrypted Message:
{encrypted_message.decode('utf-8')}
"""
# Send email
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login(smtp_username, smtp_password)
smtp.sendmail(sender, recipient, msg)
print("Encrypted email sent successfully!")
print("Save this key to decrypt:", key.decode())
OUTPUT:
Practical No. 05
Aim:To write a Python program to digitally sign a MIME email message and generate an opaque digital signature using the DKIM (dkimpy) package with the RSA algorithm
Code:
import dkim
from email.mime.text import MIMEText
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
# Generate RSA key pair
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
# Serialize private key as PKCS#1 PEM (TraditionalOpenSSL)
pem_bytes = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL, # IMPORTANT
encryption_algorithm=serialization.NoEncryption(),
)
# Create message
msg = MIMEText("This is a test message.")
msg["From"] = "sender@example.com"
msg["To"] = "recipient@example.com"
msg["Subject"] = "Test Message"
selector = b"myselector"
domain = b"example.com"
headers = [b"from", b"to", b"subject"] # use lowercase bytes
# Sign DKIM
signature = dkim.sign(
message=msg.as_bytes(),
selector=selector,
domain=domain,
privkey=pem_bytes,
include_headers=headers,)
# signature already contains "DKIM-Signature: ..."
sig_value = signature.decode().split(":", 1)[1].strip()
msg["DKIM-Signature"] = sig_value
print(msg.as_string())
OUTPUT:
CONCLUSION:Thus, DKIM signing was successfully implemented in Python. The email message was signed using an RSA private key and a valid DKIM-Signature header was added, ensuring message authenticity and integrity during transmission
Practical No. 06
Aim:Write a program to implement SSL.
CODE: Socket.py
import socket
import ssl
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Enable SSL/TLS
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="server.crt", keyfile="server.key")
# Bind the socket to a local address and port
server_address = ('localhost', 8443)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
print("Waiting for a connection...")
while True:
# Wait for a connection
connection, client_address = sock.accept()
secure_connection = None
try:
print("Connection from", client_address)
# Wrap the socket with SSL/TLS
secure_connection = context.wrap_socket(connection, server_side=True)
# Receive data from the client
data = secure_connection.recv(1024)
print("Received:", data)
# Send a response to the client
message = "Hello, client!"
secure_connection.sendall(message.encode('utf-8'))
except ssl.SSLError as e:
print("SSL Error:", e)
finally:
# Close the SSL/TLS connection
if secure_connection is not None:
secure_connection.close()
KeyCertificate.py
import os
from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.x509.oid import NameOID
from datetime import datetime, timedelta
# Generate a private key
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
# Save the private key to a file
with open("server.key", "wb") as key_file:
key_file.write(
private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
)
# Create a certificate
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, "localhost")
])
certificate = x509.CertificateBuilder().subject_name(
subject
).issuer_name(
issuer
).public_key(
private_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.utcnow()
).not_valid_after(
datetime.utcnow() + timedelta(days=365)
).add_extension(
x509.SubjectAlternativeName([x509.DNSName("localhost")]),
critical=False
).sign(private_key, hashes.SHA256())
# Save the certificate to a file
with open("server.crt", "wb") as cert_file:
cert_file.write(certificate.public_bytes(serialization.Encoding.PEM))
OUTPUT:
CONCLUSION: SSL was successfully implemented using Python socket programming. The use of digital certificates and encryption ensured secure communication between the client and server
Practical No. 07
Aim:Write SQL query to retrieve sensitive information from less sensitive queries
CODE:
CREATE TABLE mytable (
name VARCHAR(20),
gender VARCHAR(10),
race VARCHAR(10),
aid INT,
fines INT,
drugs INT,
dorm VARCHAR(10)
);
INSERT INTO mytable VALUES('Adams','M','C',5000,45,1,'Holmes');
INSERT INTO mytable VALUES('Bailey','M','B',0,0,0,'Grey');
INSERT INTO mytable VALUES('Chin','F','A',3000,20,0,'West');
INSERT INTO mytable VALUES('Dewitt','M','B',1000,35,3,'Grey');
INSERT INTO mytable VALUES('Earhart','F','C',2000,95,1,'Holmes');
INSERT INTO mytable VALUES('Fein','F','C',1000,15,0,'West');
INSERT INTO mytable VALUES('Groff','M','C',4000,0,3,'West');
INSERT INTO mytable VALUES('Hill','F','V',5000,10,2,'Holmes');
INSERT INTO mytable VALUES('Koch','F','C',0,0,1,'West');
INSERT INTO mytable VALUES('Liu','F','A',0,10,2,'Grey');
INSERT INTO mytable VALUES('Majors','M','C',2000,0,2,'Grey');
SELECT name
FROM mytable
WHERE gender='M' AND drugs=1;
CREATE TABLE female_aid AS
SELECT dorm, SUM(aid) AS f_aid
FROM mytable
WHERE gender='F'
GROUP BY dorm;
CREATE TABLE male_aid AS
SELECT dorm, SUM(aid) AS m_aid
FROM mytable
WHERE gender='M'
GROUP BY dorm;
SELECT m.dorm,
m.m_aid,
IFNULL(f.f_aid,0) AS f_aid,
m.m_aid + IFNULL(f.f_aid,0) AS total
FROM male_aid m
LEFT JOIN female_aid f
ON m.dorm = f.dorm;
SELECT dorm,
SUM(CASE WHEN gender='M' THEN 1 ELSE 0 END) AS male,
SUM(CASE WHEN gender='F' THEN 1 ELSE 0 END) AS female,
COUNT(*) AS total
FROM mytable
GROUP BY dorm;
DROP TABLE female_aid;
DROP TABLE male_aid;
OUTPUT:
create table and Insert Records
Direct Attack
Indirect SUM Attack
(a) Female Aid Table
(b) Male Aid Table
(c) Join Query
Count Attack
CONCLUSION: In this practical, we successfully created a table, inserted records, and executed SQL queries to demonstrate Direct Attack, Indirect SUM Attack, and Count Attack.
Comments
Post a Comment