0% found this document useful (0 votes)
184 views29 pages

SCP Lab Manual

The document describes how to simulate cloud computing scenarios like resource management and log forensics using CloudSim. It provides code snippets to initialize CloudSim, create data centers, virtual machines, cloudlets and run the simulation.

Uploaded by

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

SCP Lab Manual

The document describes how to simulate cloud computing scenarios like resource management and log forensics using CloudSim. It provides code snippets to initialize CloudSim, create data centers, virtual machines, cloudlets and run the simulation.

Uploaded by

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

Exp 1.

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 3: Import CloudSim libraries into your Java project.

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 6: Create a datacenter method (createDatacenter()) to define the characteristics of the


datacenter, including hosts, processing elements, RAM, storage, and bandwidth.

Step 7: Create a method (createVirtualMachines()) to generate a list of virtual machines (VMs)


with specified MIPS, RAM, bandwidth, etc.

Step 8: Submit the list of VMs to the datacenter using datacenter.submitVmList(vmList).

Step 9: Start the simulation using CloudSim.startSimulation().

Step 10: Stop the simulation after it completes using CloudSim.stopSimulation().

Step 11: Retrieve the list of finished cloudlets using datacenter.getCloudletFinishedList().

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;

public class CustomCloudSim {


public static void main(String[] args) {
int numUsers = 1;
Calendar calendar = Calendar.getInstance();
CloudSim.init(numUsers, calendar, false);

Datacenter datacenter = createDatacenter("Datacenter_0");

List<Vm> vmList = createVirtualMachines(3, 1000, 512, 1);


datacenter.submitVmList(vmList);

CloudSim.startSimulation();
CloudSim.stopSimulation();

List<Cloudlet> finishedCloudlets = datacenter.getCloudletFinishedList();


printCloudletList(finishedCloudlets);
}

private static Datacenter createDatacenter(String name) {


List<Host> hostList = new ArrayList<>();
List<Pe> peList = new ArrayList<>();
int mips = 1000;
peList.add(new Pe(0, new PeProvisionerSimple(mips)));
int ram = 2048;
long storage = 1000000;
int bw = 10000;
for (int i = 0; i < 2; i++) {
hostList.add(new Host(i, new RamProvisionerSimple(ram), new
BwProvisionerSimple(bw),
storage, peList, new VmSchedulerTimeShared(peList)));
}
return new Datacenter(name, hostList, new VmAllocationPolicySimple(hostList), new
LinkedListStorage(), 0);
}

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:

========== OUTPUT ==========


Cloudlet ID Status Data center ID VM ID Time Start Time Finish Time
0 SUCCESS 0 0 0 10.0 0.0 10.0
1 SUCCESS 0 1 1 10.0 0.0 10.0
2 SUCCESS 0 2 2 10.0 0.0 10.0
Exp 2. Simulate resource management using cloud sim

PROCEDURE:

Step 1: Import required CloudSim libraries and Java utilities.

Step 2: Define the main class named "ResourceManagementSimulation" 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 11: Start the simulation using CloudSim.startSimulation().

Step 12: Stop the simulation after it completes using CloudSim.stopSimulation().

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;

public class ResourceManagementSimulation {

public static void main(String[] args) {


CloudSim.init(1, null, false);

List<Host> hostList = new ArrayList<>();


List<Pe> peList = new ArrayList<>();
peList.add(new Pe(0, new PeProvisionerSimple(1000)));

Host host = new HostSimple(2048, 10000, 1000000, peList);


hostList.add(host);

Datacenter datacenter = new


DatacenterSimple(CloudSimEntities.DEFAULT_DATACENTER_NAME, hostList,
new VmAllocationPolicySimple(hostList), new ArrayList<>(), 0);

DatacenterBroker broker = createBroker();


int brokerId = broker.getId();

List<Vm> vmList = new ArrayList<>();


vmList.add(new VmSimple(0, brokerId, 500, 1, 512, 1000, 0, "Xen", new
CloudletSchedulerTimeShared()));
vmList.add(new VmSimple(1, brokerId, 750, 1, 512, 1000, 0, "Xen", new
CloudletSchedulerTimeShared()));
broker.submitVmList(vmList);

List<Cloudlet> cloudletList = new ArrayList<>();


cloudletList.add(new CloudletSimple(0, 500, 1));
cloudletList.add(new CloudletSimple(1, 750, 1));
broker.submitCloudletList(cloudletList);

CloudSim.startSimulation();
CloudSim.stopSimulation();

List<Cloudlet> finishedCloudlets = broker.getCloudletFinishedList();


printCloudletList(finishedCloudlets);
}
private static DatacenterBroker createBroker() {
try {
return new DatacenterBrokerSimple("Broker");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

private static void printCloudletList(List<Cloudlet> list) {


System.out.println("\n========== OUTPUT ==========");
System.out.println("Cloudlet ID\tStatus\tData center ID\tVM ID\tTime\tStart Time\tFinish
Time");
DecimalFormat dft = new DecimalFormat("###.##");
for (Cloudlet cloudlet : list) {
String status = cloudlet.getStatus() == Cloudlet.SUCCESS ? "SUCCESS" : "FAILED";
System.out.printf("%d\t%s\t%d\t%d\t%s\t%s\t%s%n", cloudlet.getCloudletId(), status,
cloudlet.getResourceId(), cloudlet.getVmId(),
dft.format(cloudlet.getActualCPUTime()),
dft.format(cloudlet.getExecStartTime()), dft.format(cloudlet.getFinishTime()));
}
}
}

OUTPUT :

========== OUTPUT ==========


Cloudlet ID Status Data center ID VM ID Time Start Time Finish Time
0 SUCCESS 0 0 500.00 0.00 500.00
1 SUCCESS 0 1 750.00 500.00 1250.00
Exp 3.Simulate log forensics using cloud sim

PROCEDURE:

Step 1: Import required CloudSim libraries and Java utilities.

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 11: Start the simulation using CloudSim.startSimulation().

Step 12: Stop the simulation after it completes using CloudSim.stopSimulation().

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;

public class LogForensicsSimulation {

public static void main(String[] args) {


CloudSim.init(1, null, false);

List<Host> hostList = new ArrayList<>();


List<Pe> peList = new ArrayList<>();
peList.add(new Pe(0, new PeProvisionerSimple(1000)));

Host host = new HostSimple(2048, 10000, 1000000, peList);


hostList.add(host);

Datacenter datacenter = new


DatacenterSimple(CloudSimEntities.DEFAULT_DATACENTER_NAME, hostList,
new VmAllocationPolicySimple(hostList), new ArrayList<>(), 0);

DatacenterBroker broker = createBroker();


int brokerId = broker.getId();

List<Vm> vmList = new ArrayList<>();


vmList.add(new VmSimple(0, brokerId, 500, 1, 512, 1000, 0, "Xen", new
CloudletSchedulerTimeShared()));
vmList.add(new VmSimple(1, brokerId, 750, 1, 512, 1000, 0, "Xen", new
CloudletSchedulerTimeShared()));
broker.submitVmList(vmList);

List<Cloudlet> cloudletList = new ArrayList<>();


cloudletList.add(new CloudletSimple(0, 500, 1));
cloudletList.add(new CloudletSimple(1, 750, 1));
broker.submitCloudletList(cloudletList);

CloudSim.startSimulation();
CloudSim.stopSimulation();

List<Cloudlet> finishedCloudlets = broker.getCloudletFinishedList();


printCloudletList(finishedCloudlets);
}

private static DatacenterBroker createBroker() {


try {
return new DatacenterBrokerSimple("Broker");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

private static void printCloudletList(List<Cloudlet> list) {


System.out.println("\n========== OUTPUT ==========");
System.out.println("Cloudlet ID\tStatus\tData center ID\tVM ID\tTime\tStart Time\tFinish
Time");
DecimalFormat dft = new DecimalFormat("###.##");
for (Cloudlet cloudlet : list) {
String status = cloudlet.getStatus() == Cloudlet.SUCCESS ? "SUCCESS" : "FAILED";
System.out.printf("%d\t%s\t%d\t%d\t%s\t%s\t%s%n", cloudlet.getCloudletId(), status,
cloudlet.getResourceId(), cloudlet.getVmId(),
dft.format(cloudlet.getActualCPUTime()),
dft.format(cloudlet.getExecStartTime()), dft.format(cloudlet.getFinishTime()));
}
}
}

OUTPUT:

========== OUTPUT ==========


Cloudlet ID Status Data center ID VM ID Time Start Time Finish Time
0 SUCCESS 0 0 500.00 0.00 500.00
1 SUCCESS 0 1 750.00 500.00 1250.00
Exp 4.Simulate a secure file sharing using a cloud sim.

PROCEDURE:

Step 1: Import required CloudSim libraries and Java utilities.

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 11: Start the simulation using CloudSim.startSimulation().

Step 12: Stop the simulation after it completes using CloudSim.stopSimulation().

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;

public class SecureFileSharingSimulation {

public static void main(String[] args) {


CloudSim.init(1, null, false);

List<Host> hostList = new ArrayList<>();


List<Pe> peList = new ArrayList<>();
peList.add(new Pe(0, new PeProvisionerSimple(1000)));

Host host = new HostSimple(2048, 10000, 1000000, peList);


hostList.add(host);

Datacenter datacenter = new


DatacenterSimple(CloudSimEntities.DEFAULT_DATACENTER_NAME, hostList,
new VmAllocationPolicySimple(hostList), new ArrayList<>(), 0);

DatacenterBroker broker = createBroker();


int brokerId = broker.getId();

List<Vm> vmList = new ArrayList<>();


vmList.add(new VmSimple(0, brokerId, 1000, 1, 512, 1000, 0, "Xen", new
VmSchedulerTimeShared()));
broker.submitVmList(vmList);

List<Cloudlet> cloudletList = new ArrayList<>();


cloudletList.add(new CloudletSimple(0, 500, 1));
cloudletList.add(new CloudletSimple(1, 750, 1));
broker.submitCloudletList(cloudletList);

CloudSim.startSimulation();
CloudSim.stopSimulation();

List<Cloudlet> finishedCloudlets = broker.getCloudletFinishedList();


printCloudletList(finishedCloudlets);
}

private static DatacenterBroker createBroker() {


try {
return new DatacenterBrokerSimple("Broker");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

private static void printCloudletList(List<Cloudlet> list) {


System.out.println("\n========== OUTPUT ==========");
System.out.println("Cloudlet ID\tStatus\tData center ID\tVM ID\tTime\tStart Time\tFinish
Time");
DecimalFormat dft = new DecimalFormat("###.##");
for (Cloudlet cloudlet : list) {
String status = cloudlet.getStatus() == Cloudlet.SUCCESS ? "SUCCESS" : "FAILED";
System.out.printf("%d\t%s\t%d\t%d\t%s\t%s\t%s%n", cloudlet.getCloudletId(), status,
cloudlet.getResourceId(), cloudlet.getVmId(),
dft.format(cloudlet.getActualCPUTime()),
dft.format(cloudlet.getExecStartTime()), dft.format(cloudlet.getFinishTime()));
}
}
}

OUTPUT:

========== OUTPUT ==========


Cloudlet ID Status Data center ID VM ID Time Start Time Finish Time
0 SUCCESS 0 0 500.00 0.00 500.00
1 SUCCESS 0 0 750.00 500.00 1250.00
Exp 5.Implement data anonymization techniques over the simple dataset (masking,
k-anonymization, etc)

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 11: Set the value of k for k-anonymization.

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;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

class DataAnonymization {

public static List<Person> maskData(List<Person> originalData) {


List<Person> maskedData = new ArrayList<>();
for (Person person : originalData) {
String maskedName = maskString(person.getName());
int maskedAge = maskInt(person.getAge());
maskedData.add(new Person(maskedName, maskedAge));
}
return maskedData;
}

public static List<Person> kAnonymizeData(List<Person> originalData, int k) {


List<Person> anonymizedData = new ArrayList<>();
List<Person> temp = new ArrayList<>(originalData);
while (!temp.isEmpty()) {
List<Person> group = new ArrayList<>();
for (int i = 0; i < k && !temp.isEmpty(); i++) {
Random rand = new Random();
int randomIndex = rand.nextInt(temp.size());
group.add(temp.remove(randomIndex));
}
anonymizedData.addAll(maskGroup(group));
}
return anonymizedData;
}

private static List<Person> maskGroup(List<Person> group) {


List<Person> maskedGroup = new ArrayList<>();
String maskedName = maskString(group.get(0).getName());
for (Person person : group) {
maskedGroup.add(new Person(maskedName, maskInt(person.getAge())));
}
return maskedGroup;
}

private static String maskString(String originalString) {


return originalString.replaceAll(".", "*");
}

private static int maskInt(int originalInt) {


return (originalInt / 10) * 10; // Masking by rounding down to the nearest multiple of 10
}
}

public class Main {


public static void main(String[] args) {
List<Person> originalData = new ArrayList<>();
originalData.add(new Person("Alice", 25));
originalData.add(new Person("Bob", 35));
originalData.add(new Person("Charlie", 40));

System.out.println("Original Data:");
originalData.forEach(System.out::println);

List<Person> maskedData = DataAnonymization.maskData(originalData);


System.out.println("\nMasked Data:");
maskedData.forEach(System.out::println);
int k = 2; // Setting k value for k-anonymization
List<Person> anonymizedData = DataAnonymization.kAnonymizeData(originalData, k);
System.out.println("\nK-Anonymized Data (k=" + k + "):");
anonymizedData.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}

K-Anonymized Data (k=2):


Person{name='***', age=20}
Person{name='***', age=30}
Person{name='*******', age=40}
EXP 6. Implement any encryption algorithm to protect the images

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 8: Define the flatten_image function to flatten a given image array.

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 12: Read an input image using OpenCV's cv2.imread function.

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 5: Save Encrypted Image: The encrypted image is saved as "encrypted.png".

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

from PIL import Image


import numpy as np
import random
import sys

def image_obfuscator(mode, source_file, key=None):


try:
IMAGE_SOURCE = Image.open(source_file)
img_arr = np.array(IMAGE_SOURCE)
img_rows, img_cols, _ = img_arr.shape
except Exception as e:
print("\nError while loading source image! Did you specify a valid path?")
print(e)
sys.exit(1)

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")

elif mode == "decrypt":


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_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

# Call the function


image_obfuscator(MODE, SOURCE_FILE, 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 5: Instantiate the FileStorageRBAC class: Create an instance of the FileStorageRBAC


class named file_storage_rbac.

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

Permissions for admin_user:


Read: True
Write: True
Delete: True

Permissions for manager_user:


Read: True
Write: True

Permissions for employee_user:


Read: True
EXP 9.Implement an attribute-based access control mechanism based on a particular
scenario

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 5: Create an instance of the ABAC class named abac.

Step 6: Define access rules for different roles: Admin, Manager, and Employee.

Step 7: Create resources with different sensitivity levels.

Step 8: Simulate access checks for various scenarios.

Step 9: Print the results of the access checks.

PROGRAM :
class Resource:
def __init__(self, sensitivity):
self.sensitivity = sensitivity

class ABAC:
def __init__(self):
self.access_rules = []

def add_access_rule(self, role, location, sensitivity, allow_access):


self.access_rules.append({
"role": role,
"location": location,
"sensitivity": sensitivity,
"allow_access": allow_access
})

def check_access(self, user_role, user_location, resource):


for rule in self.access_rules:
if (rule["role"] == user_role and
rule["location"] == user_location and
rule["sensitivity"] == resource.sensitivity):
return rule["allow_access"]
return False

# Example usage:

# Create ABAC instance


abac = ABAC()

# Define access rules


# Admin can access all resources from both internal and external networks
abac.add_access_rule("admin", "IN", "low", True)
abac.add_access_rule("admin", "IN", "medium", True)
abac.add_access_rule("admin", "IN", "high", True)
abac.add_access_rule("admin", "EN", "low", True)
abac.add_access_rule("admin", "EN", "medium", True)
abac.add_access_rule("admin", "EN", "high", True)

# 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")

# Simulate access checks


print("Access Check Results:")
print("Admin accessing low sensitivity resource from internal network:",
abac.check_access("admin", "IN", low_sensitivity_resource))
print("Manager accessing high sensitivity resource from external network:",
abac.check_access("manager", "EN", high_sensitivity_resource))
print("Employee accessing medium sensitivity resource from internal network:",
abac.check_access("employee", "IN", medium_sensitivity_resource))
OUTPUT

Access Check Results:


Admin accessing low sensitivity resource from internal network: True
Manager accessing high sensitivity resource from external network: False
Employee accessing medium sensitivity resource from internal network: False
EXP 10.. Develop a log monitoring system with incident management in the cloud

PROCEDURE:

Step 1: Import the necessary module time for time-related functions and random for generating
random log entries.

Step 2: Define the LogMonitor class representing a log monitoring system.

Step 3: Initialize the incidents list in the constructor to store detected incidents.

Step 4: Implement the monitor_logs method to continuously monitor logs.

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 7: If an incident is detected, manage it using the manage_incident method.

Step 8: Sleep for 1 second before checking the logs again to avoid continuous checking.

Step 9: Define the read_log method to generate random log entries.

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.

Step 13: Call the monitor_logs method to start monitoring logs.

PROGRAM

import timeStep 13:


import random
class LogMonitor:
def __init__(self):
self.incidents = []
def monitor_logs(self):
while True:
log = self.read_log()
if self.detect_incident(log):
self.manage_incident(log)
time.sleep(1)
def read_log(self):
logs = [
"Error: Out of memory",
"Warning: High CPU usage",
"Error: Disk full",
"Info: Application started",
"Error: Database connection failed"
]
return random.choice(logs)
def detect_incident(self, log):
return "Error" in log
def manage_incident(self, log):
print("Incident detected:", log)
self.incidents.append(log)

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

You might also like