SCP Lab Manual
SCP Lab Manual
Simulate a cloud scenario using CloudSim and run a scheduling algorithm not
present in CloudSim
PROCEDURE:
Step 1: Download and install CloudSim from the official website or repository.
Step 2: Create a Java project dedicated to your CloudSim experiment in your preferred IDE.
Step 4: Define a Java class named CustomCloudSim to encapsulate your cloud simulation
experiment.
Step 5: Initialize CloudSim by setting the number of users, creating a calendar instance, and
calling CloudSim.init().
Step 12: Print relevant details like cloudlet ID, status, data center ID, VM ID, execution time,
start time, and finish time using the printCloudletList() method.
PROGRAM:
import org.cloudbus.cloudsim.*;
import org.cloudbus.cloudsim.core.CloudSim;
import java.util.ArrayList;
import java.util.List;
CloudSim.startSimulation();
CloudSim.stopSimulation();
private static List<Vm> createVirtualMachines(int numVMs, int mips, int ram, int bw) {
List<Vm> vmList = new ArrayList<>();
for (int i = 0; i < numVMs; i++) {
Vm vm = new Vm(i, 0, mips, 1, ram, bw, 0, "Xen", new
CloudletSchedulerSpaceShared());
vmList.add(vm);
}
return vmList;
}
private static void printCloudletList(List<Cloudlet> list) {
int size = list.size();
Cloudlet cloudlet;
String indent = " ";
System.out.println();
System.out.println("========== OUTPUT ==========");
System.out.println("Cloudlet ID" + indent + "Status" + indent + "Data center ID" + indent +
"VM ID" + indent + "Time" + indent + "Start Time" + indent + "Finish Time");
DecimalFormat dft = new DecimalFormat("###.##");
for (int i = 0; i < size; i++) {
cloudlet = list.get(i);
System.out.print(indent + cloudlet.getCloudletId() + indent + indent);
if (cloudlet.getStatus() == Cloudlet.SUCCESS) {
System.out.print("SUCCESS");
System.out.print(indent + indent + cloudlet.getResourceId() + indent + indent + indent
+ cloudlet.getVmId() + indent + indent + dft.format(cloudlet.getActualCPUTime()) + indent +
indent + dft.format(cloudlet.getExecStartTime()) + indent + indent +
dft.format(cloudlet.getFinishTime()));
}
System.out.println();
}
}
}
OUTPUT:
PROCEDURE:
Step 3: Initialize CloudSim with one user and no specific calendar instance.
Step 4: Create a list to hold host objects and a list to hold processing element (PE) objects.
Step 5: Add a processing element to the PE list with a MIPS capacity of 1000.
Step 6: Create a host with specified characteristics such as RAM, bandwidth, storage, and PE
list.
Step 7: Create a datacenter with the default name, host list, a simple VM allocation policy, and
an empty list for storage.
Step 8: Create a broker for managing interactions between the cloud infrastructure and users.
Step 9: Generate VMs with specific parameters like MIPS, RAM, bandwidth, etc., and add them
to the broker.
Step 10: Generate cloudlets with specific length and number of PEs, and add them to the
broker.
Step 13: Retrieve the list of finished cloudlets from the broker.
Step 14: Print relevant details of finished cloudlets such as ID, status, data center ID, VM ID,
execution time, start time, and finish time using the printCloudletList() method.
PROGRAM:
import org.cloudbus.cloudsim.*;
import org.cloudbus.cloudsim.core.CloudSim;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
CloudSim.startSimulation();
CloudSim.stopSimulation();
OUTPUT :
PROCEDURE:
Step 2: Define the main class named "LogForensicsSimulation" to manage the simulation.
Step 3: Initialize CloudSim with one user and no specific calendar instance.
Step 4: Create a list to hold host objects and a list to hold processing element (PE) objects.
Step 5: Add a processing element to the PE list with a MIPS capacity of 1000.
Step 6: Create a host with specified characteristics such as RAM, bandwidth, storage, and PE
list.
Step 7: Create a datacenter with the default name, host list, a simple VM allocation policy, and
an empty list for storage.
Step 8: Create a broker for managing interactions between the cloud infrastructure and users.
Step 9: Generate VMs with specific parameters like MIPS, RAM, bandwidth, etc., and add them
to the broker.
Step 10: Generate cloudlets with specific length and number of PEs, and add them to the
broker.
Step 13: Retrieve the list of finished cloudlets from the broker.
Step 14: Print relevant details of finished cloudlets such as ID, status, data center ID, VM ID,
execution time, start time, and finish time using the printCloudletList() method.
PROGRAM:
import org.cloudbus.cloudsim.*;
import org.cloudbus.cloudsim.core.CloudSim;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
CloudSim.startSimulation();
CloudSim.stopSimulation();
OUTPUT:
PROCEDURE:
Step 2: Define the main class named "SecureFileSharingSimulation" to manage the simulation.
Step 3: Initialize CloudSim with one user and no specific calendar instance.
Step 4: Create a list to hold host objects and a list to hold processing element (PE) objects.
Step 5: Add a processing element to the PE list with a MIPS capacity of 1000.
Step 6: Create a host with specified characteristics such as RAM, bandwidth, storage, and PE
list.
Step 7: Create a datacenter with the default name, host list, a simple VM allocation policy, and
an empty list for storage.
Step 8: Create a broker for managing interactions between the cloud infrastructure and users.
Step 9: Generate VMs with specific parameters like MIPS, RAM, bandwidth, etc., and add them
to the broker.
Step 10: Generate cloudlets with specific length and number of PEs, and add them to the
broker.
Step 13: Retrieve the list of finished cloudlets from the broker.
Step 14: Print relevant details of finished cloudlets such as ID, status, data center ID, VM ID,
execution time, start time, and finish time using the printCloudletList() method.
PROGRAM
import org.cloudbus.cloudsim.*;
import org.cloudbus.cloudsim.core.CloudSim;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
CloudSim.startSimulation();
CloudSim.stopSimulation();
OUTPUT:
PROCEDURE:
Step 1: Define a Person class to represent individual data entities with attributes such as name
and age.
Step 2: Implement a DataAnonymization class with methods to mask individual data attributes
and anonymize data groups.
Step 3: Implement a method maskData to mask the name and age of each person in the
original data list.
Step 4: Implement a method kAnonymizeData to anonymize the original data list by grouping
individuals into k-anonymized groups and masking their attributes.
Step 5: Implement helper methods maskGroup to mask the attributes of a group of individuals
and maskString / maskInt to mask individual string and integer values.
Step 6: Define a Main class with the main method to demonstrate the usage of the Person class
and DataAnonymization methods.
Step 7: Create an original data list containing Person objects with name and age attributes.
Step 8: Print the original data list to display the unmodified data.
Step 9: Mask the data attributes (name and age) of each person in the original data list using
the maskData method.
Step 10: Print the masked data list to display the data with masked attributes.
Step 12: Anonymize the original data list using the kAnonymizeData method with the specified
value of k.
Step 13: Print the k-anonymized data list to display the anonymized data with masked attributes
and grouped individuals.
PROGRAM:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
class DataAnonymization {
System.out.println("Original Data:");
originalData.forEach(System.out::println);
OUTPUT
Original Data:
Person{name='Alice', age=25}
Person{name='Bob', age=35}
Person{name='Charlie', age=40}
Masked Data:
Person{name='*****', age=20}
Person{name='***', age=30}
Person{name='*******', age=40}
PROCEDURE:
Step 1: Import necessary libraries including numpy, math, cv2 (OpenCV), random, and
matplotlib.
Step 2: Define the is_prime function to check whether a given number is prime.
Step 3: Define the generate_primes function to generate two random prime numbers.
Step 4: Define the generate_E function to generate a coprime number with a given value.
Step 5: Define the generate_D function to generate a private key based on a given modulus
and public key.
Step 6: Define the generate_key_pair function to generate a pair of public and private keys for
RSA encryption.
Step 7: Define the encrypt_image function to encrypt an image using RSA encryption.
Step 9: Define the reshape_image function to reshape a flattened image array to its original
shape.
Step 10: Define the conver_flat_2_3D function to convert a flattened image array back to a 3D
image array.
Step 11: Define the RSA_encryption function to perform RSA encryption on an input image.
Step 13: Call the RSA_encryption function passing the input image as an argument.
Step 14: The RSA_encryption function generates a pair of public and private keys, encrypts the
input image using RSA encryption, and saves the encrypted image to a file named
"encrypted_image.jpg".
PROGRAM
import numpy as np
import math
import cv2
import random
import matplotlib.pyplot as plt
def is_prime(number):
if number <= 1:
return False
else:
for i in range(2, number):
if number % i == 0:
return False
return True
def generate_primes():
while True:
prime1 = random.randint(100, 1000)
prime2 = random.randint(100, 1000)
if is_prime(prime1) and is_prime(prime2) and prime1 != prime2:
return prime1, prime2
def generate_E(m):
coprime_number = 2
while math.gcd(m, coprime_number) != 1:
coprime_number = random.randint(2, m - 1)
return coprime_number
def generate_D(M, E):
k=1
while True:
d = (((M * k) + 1) / E)
if d == int(d):
return int(d)
k += 1
def generate_key_pair():
p, q = generate_primes()
n=p*q
m = (p - 1) * (q - 1)
e = generate_E(m)
d = generate_D(m, e)
return p, q, n, m, e, d
def encrypt_image(flatten_image, E, modulus):
encrypted_text = [pow(int(flatten_image[i]), E, modulus) for i in range(len(flatten_image))]
encrypted_text = np.array(encrypted_text)
return encrypted_text
def flatten_image(image_array):
flattened_image = image_array.flatten()
return flattened_image
def reshape_image(flattened_image, height, width):
reshaped_image = flattened_image.reshape(height, width, 3)
return reshaped_image
def conver_flat_2_3D(flat_image, h, w):
for pixel in flat_image:
flat_image[pixel] = flat_image[pixel] % 256
flat_image = flat_image.astype(np.uint8)
flat_image = reshape_image(flat_image, h, w)
return flat_image
def RSA_encryption(img):
height, width = img.shape[:2]
p, q, n, m, E, D = generate_key_pair()
flat_array_of_original_image = flatten_image(img)
encrypted_image_text = encrypt_image(flat_array_of_original_image, E, n)
encrypted_image_img= conver_flat_2_3D(encrypted_image_text, height, width)
encrypted_image_img= cv2.cvtColor(encrypted_image_img, cv2.COLOR_BGR2GRAY)
cv2.imwrite("encrypted_image.jpg", encrypted_image_img*2)
img = cv2.imread("./images/apple.jpg")
RSA_encryption(img)
OUTPUT
EXP 7. Implement any image obfuscation mechanism
PROCEDURE:
Step 1: Import necessary libraries including Image from PIL, numpy, random, and sys.
Step 2: Define the image_obfuscator function: This function takes three parameters - mode,
source_file, and key (optional). It either encrypts or decrypts the source image based on the
mode.
Step 3: Load the Source Image: The source image is loaded using PIL's Image.open function,
and then converted into a numpy array.
Step 4: Encrypt Mode: If the mode is set to "encrypt", a random key is generated if no key is
provided. Each pixel value of the source image is XORed with the corresponding pixel value of
the key image.
Step 6: Generate and Save Key (if applicable): If no key is provided and the mode is "encrypt",
a random key is generated and saved as "key.png".
Step 7: Decrypt Mode: If the mode is set to "decrypt", the key image is loaded, and each pixel
value of the encrypted image is XORed with the corresponding pixel value of the key image.
Step 8: Show and Save Decrypted Image: The decrypted image is displayed and saved as
"decrypted.png".
Step 9: Main Function: Set the parameters including the mode ("encrypt" or "decrypt"), source
file path, and key file path (if applicable).
Step 10: Call the image_obfuscator function with the specified parameters.
PROGRAM
if mode == "encrypt":
if key is None:
key_arr = np.random.randint(0, 256, size=(img_rows, img_cols, 3), dtype=np.uint8)
else:
try:
IMAGE_KEY = Image.open(key)
key_arr = np.array(IMAGE_KEY)
except Exception as e:
print("\nError while loading key! Did you specify a valid path?")
print(e)
sys.exit(1)
for i in range(img_rows):
for j in range(img_cols):
for k in range(3):
img_arr[i][j][k] = int(img_arr[i][j][k]) ^ int(key_arr[i][j][k])
IMAGE_ENCRYPTED = Image.fromarray(img_arr)
IMAGE_ENCRYPTED.save("encrypted.png")
if key is None:
IMAGE_KEY = Image.fromarray(key_arr)
IMAGE_KEY.save("key.png")
for i in range(img_rows):
for j in range(img_cols):
for k in range(3):
img_arr[i][j][k] = int(img_arr[i][j][k]) ^ int(key_arr[i][j][k])
IMAGE_DECRYPTED = Image.fromarray(img_arr)
IMAGE_DECRYPTED.show()
IMAGE_DECRYPTED.save("decrypted.png")
if __name__ == "__main__":
# Set parameters here
MODE = "encrypt" # or "decrypt"
SOURCE_FILE = "./demo.jpg"
KEY = "./key.png" # Use None if you want to generate a random key
OUTPUT
EXP 8.. Implement a role-based access control mechanism in a specific scenario
PROCEDURE:
Step 1: Define the FileStorageRBAC class: This class represents a Role-Based Access Control
(RBAC) system for file storage. It initializes with predefined roles and an empty dictionary to
store users and their roles.
Step 2: Define the __init__ method: This method initializes the roles dictionary with predefined
roles and their associated permissions, and initializes the users dictionary to store users and
their roles.
Step 3: Define the add_user method: This method allows adding users to the RBAC system by
specifying their username and role.
Step 4: Define the check_permission method: This method checks whether a given user has a
specific permission. It checks if the user exists in the users dictionary, retrieves the user's role,
and then checks if the role has the requested permission.
Step 6: Add users to the RBAC system: Add users with their respective roles using the
add_user method.
Step 7: Define users_permissions dictionary: This dictionary specifies the permissions for each
user.
Step 8: Iterate over users and their permissions: Loop through the users_permissions dictionary
and print the permissions for each user using the check_permission method.
Step 9: Print the permissions: Print the permissions for each user, indicating whether they have
the specified permission or not.
PROGRAM
class FileStorageRBAC:
def __init__(self):
self.roles = {"admin": ["read", "write", "delete"],"manager": ["read", "write"],"employee":
["read"] }
self.users = {}
def add_user(self, username, role):
self.users[username] = role
def check_permission(self, username, permission):
if username in self.users:
role = self.users[username]
if role in self.roles:
return permission in self.roles[role]
return False
file_storage_rbac = FileStorageRBAC()
file_storage_rbac.add_user("admin_user", "admin")
file_storage_rbac.add_user("manager_user", "manager")
file_storage_rbac.add_user("employee_user", "employee")
users_permissions = {"admin_user": ["read", "write", "delete"],"manager_user": ["read",
"write"],"employee_user": ["read"]}
for user, permissions in users_permissions.items():
print(f"Permissions for {user}:")
for permission in permissions:
print(f"{permission.capitalize()}: {file_storage_rbac.check_permission(user, permission)}")
print()
OUTPUT
PROCEDURE:
Step 1: Define the Resource class to represent resources with a sensitivity level.
Step 2: Implement the ABAC class for Attribute-Based Access Control (ABAC) system.
Step 3: Add access rules to the ABAC system using the add_access_rule method.
Step 4: Check if a user has access to a resource with the check_access method.
Step 6: Define access rules for different roles: Admin, Manager, and Employee.
PROGRAM :
class Resource:
def __init__(self, sensitivity):
self.sensitivity = sensitivity
class ABAC:
def __init__(self):
self.access_rules = []
# Example usage:
# Manager can access low and medium sensitivity resources from both networks
abac.add_access_rule("manager", "IN", "low", True)
abac.add_access_rule("manager", "IN", "medium", True)
abac.add_access_rule("manager", "EN", "low", True)
abac.add_access_rule("manager", "EN", "medium", True)
# Employee can access only low sensitivity resources from the internal network
abac.add_access_rule("employee", "IN", "low", True)
# Create resources
low_sensitivity_resource = Resource("low")
medium_sensitivity_resource = Resource("medium")
high_sensitivity_resource = Resource("high")
PROCEDURE:
Step 1: Import the necessary module time for time-related functions and random for generating
random log entries.
Step 3: Initialize the incidents list in the constructor to store detected incidents.
Step 5: Inside the monitor_logs method, read a log entry using the read_log method.
Step 6: Check if the log indicates an incident using the detect_incident method.
Step 8: Sleep for 1 second before checking the logs again to avoid continuous checking.
Step 10: Define the detect_incident method to check if the log contains an "Error" entry.
Step 11: Define the manage_incident method to handle detected incidents by printing the
incident and adding it to the incidents list.
Step 12: In the main block, create an instance of the LogMonitor class named monitor.
PROGRAM
if __name__ == "__main__":
monitor = LogMonitor()
monitor.monitor_logs()
OUTPUT
Incident detected: Error: Out of memory
Incident detected: Error: Disk full
Incident detected: Error: Database connection failed