Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- PRACTICAL NO. 1
- Demonstrate techniques for file and data integrity.
- Data Integrity :
- User1.java
- import java.net.*;
- import java.io.*;
- import java.util.*;
- import java.io.UnsupportedEncodingException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.Arrays;
- import java.util.Base64;
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;
- class User1
- {
- DatagramSocket d;
- DatagramPacket p,p1;
- int i=0;
- private static SecretKeySpec secretKey;
- private static byte[] key;
- final String Keys = "ssshhhhhhhhhhh!!!!";
- User1()
- {
- try
- {
- d=new DatagramSocket(1000);
- for(i=0;i<20;i++)
- {
- System.out.println("Enter a msg");
- Scanner sc=new Scanner(System.in);
- String msg=sc.next();
- String encryptedString = User1.encrypt(msg,Keys) ;
- p=new DatagramPacket(encryptedString.getBytes(),encryptedString.length(),InetAddress.getLocalHost(),2000);
- d.send(p);
- System.out.println("Encrypted Msg "+encryptedString);
- System.out.println("msg sent");
- receive();
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- public void receive()
- {
- try
- {
- byte b[]=new byte[1024];
- p1=new DatagramPacket(b,b.length);
- d.receive(p1);
- String s=new String(p1.getData());
- String decryptedString = User1.decrypt(s.trim(),Keys) ;
- System.out.println(decryptedString);
- System.out.println(s.trim());
- }
- catch(Exception ex)
- {
- ex.printStackTrace();
- }
- }
- public static void setKey(String myKey)
- {
- MessageDigest sha = null;
- try {
- key = myKey.getBytes("UTF-8");
- sha = MessageDigest.getInstance("SHA-1");
- key = sha.digest(key);
- key = Arrays.copyOf(key, 16);
- secretKey = new SecretKeySpec(key, "AES");
- }
- catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- public static String encrypt(String strToEncrypt, String secret)
- {
- try
- {
- setKey(secret);
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, secretKey);
- return Base64.getEncoder().withoutPadding().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
- }
- catch (Exception e)
- {
- System.out.println("Error while encrypting: " + e.toString());
- }
- return null;
- }
- public static String decrypt(String strToDecrypt, String secret)
- {
- try
- {
- setKey(secret);
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
- cipher.init(Cipher.DECRYPT_MODE, secretKey);
- return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
- }
- catch (Exception e)
- {
- System.out.println("Error while decrypting: " + e.toString());
- }
- return null;
- }
- public static void main(String s[])
- {
- new User1();
- }
- }
- User2.java
- import java.net.*;
- import java.io.*;
- import java.util.*;
- import java.net.*;
- import java.io.*;
- import java.util.*;
- import java.io.UnsupportedEncodingException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.Arrays;
- import java.util.Base64;
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;class User2
- {
- DatagramSocket d;
- DatagramPacket p,p1;
- int i=0;
- private static SecretKeySpec secretKey;
- private static byte[] key;
- final String Keys = "ssshhhhhhhhhhh!!!!";
- User2()
- {
- try
- {
- d=new DatagramSocket(2000);
- for(i=0;i<20;i++)
- {
- byte b[]=new byte[1024];
- p1=new DatagramPacket(b,b.length);
- d.receive(p1);
- String s=new String(p1.getData());
- //byte[]text=s.getBytes();
- System.out.println(s.trim());
- String decryptedString = User2.decrypt(s.trim(),Keys) ;
- System.out.println(decryptedString);
- send();
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- public void send()
- {
- try
- {
- System.out.println("Enter a msg");
- Scanner sc=new Scanner(System.in);
- String msg=sc.next();
- String encryptedString = User2.encrypt(msg,Keys) ;
- p=new DatagramPacket(encryptedString.getBytes(),encryptedString.length(),InetAddress.getLocalHost(),2000);
- d.send(p);
- System.out.println("Encrypted Msg "+encryptedString);
- System.out.println("msg sent");
- }
- catch(Exception ex)
- {
- ex.printStackTrace();
- }
- }
- public static void setKey(String myKey)
- {
- MessageDigest sha = null;
- try {
- key = myKey.getBytes("UTF-8");
- sha = MessageDigest.getInstance("SHA-1");
- key = sha.digest(key);
- key = Arrays.copyOf(key, 16);
- secretKey = new SecretKeySpec(key, "AES");
- }
- catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- public static String encrypt(String strToEncrypt, String secret)
- {
- try
- {
- setKey(secret);
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, secretKey);
- return Base64.getEncoder().withoutPadding().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
- }
- catch (Exception e)
- {
- System.out.println("Error while encrypting: " + e.toString());
- }
- return null;
- }
- public static String decrypt(String strToDecrypt, String secret)
- {
- try
- {
- setKey(secret);
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
- cipher.init(Cipher.DECRYPT_MODE, secretKey);
- return new String(cipher.doFinal(Base64.getMimeDecoder().decode(strToDecrypt)));
- }
- catch (Exception e)
- {
- System.out.println("Error while decrypting: " + e.toString());
- }
- return null;
- }
- public static void main(String s[])
- {
- new User2();
- }
- }
- Output :
- File Integrity :
- Server.java
- import java.util.*;
- import javax.swing.*;
- import java.awt.*;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.net.*;
- import java.io.*;
- import java.util.*;
- import java.security.*;
- class Server extends JFrame implements ActionListener
- {
- JLabel l1;
- JTextField t1;
- JTextArea ta;
- JButton b1,b2,b3;
- Socket s;
- ServerSocket ss;
- String z,x,y,hash;
- String m[];
- JScrollPane scroll;
- Server()
- {
- super("Server");
- try
- {
- ss=new ServerSocket(1000);
- s=ss.accept();
- l1=new JLabel("File Name:- ");
- t1=new JTextField(20);
- ta=new JTextArea(20,30);
- scroll = new JScrollPane(ta);
- b2=new JButton("Open");
- b3=new JButton("Check Integrity");
- setLayout(new FlowLayout());
- add(l1);
- add(t1);
- add(b2);
- add(b3);
- add(scroll);
- setSize(600,600);
- setVisible(true);
- b2.addActionListener(this);
- b3.addActionListener(this);
- InputStream in=s.getInputStream();
- InputStream in2=s.getInputStream();
- byte b[]=new byte[4096];
- byte b2[]=new byte[1024];
- in.read(b);
- in2.read(b2);
- String msg=new String(b);
- String h=new String(b2);
- m=msg.trim().split(" ");
- System.out.println(m[0]);
- System.out.println(h);
- t1.setText(m[0]);
- hash=h.trim();
- System.out.println("Generated Hash:-" + hash);
- setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- public static void main(String args[])
- {
- new Server();
- }
- public void actionPerformed(ActionEvent e)
- {
- Object o=e.getSource();
- if(b2==o)
- {
- for(int i=1;i<m.length;i++)
- ta.append(m[i] + " ");
- }
- if(b3==o)
- {
- try
- {
- MessageDigest digest = MessageDigest.getInstance("MD5");
- byte[] inputBytes =ta.getText().trim().getBytes();
- digest.update(inputBytes);
- byte[] hashBytes = digest.digest();
- System.out.println("Calculated HashCode: - " + new String(hashBytes));
- if(hash.equals(new String(hashBytes)))
- {
- System.out.println("File Integrity is maintained");
- }
- else
- {
- System.out.println("File Integrity is not maintained");
- }
- }
- catch(Exception e1)
- {
- e1.printStackTrace();
- }
- }
- }
- }
- Client.java
- import java.util.*;
- import javax.swing.*;
- import java.awt.*;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.net.*;
- import java.io.*;
- import java.util.*;
- import java.security.*;
- class Client extends JFrame implements ActionListener
- {
- JLabel l1;
- JTextField t1;
- JTextArea ta;
- JButton b1,b2;
- Socket s;
- String z,x,y,hash;
- byte b[];
- Client()
- {
- super("Client");
- try
- {
- s=new Socket(InetAddress.getByName("localhost"),1000);
- b1=new JButton("browse");
- t1=new JTextField(20);
- b2=new JButton("send");
- setLayout(new FlowLayout());
- add(b1);
- add(t1);
- add(b2);
- setSize(400,400);
- setVisible(true);
- b1.addActionListener(this);
- b2.addActionListener(this);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- public static void main(String args[])
- {
- new Client();
- }
- public void actionPerformed(ActionEvent e)
- {
- Object o=e.getSource();
- if(b1==o)
- {
- try
- {
- JFileChooser f=new JFileChooser();
- f.showOpenDialog(null);
- File d=f.getSelectedFile();
- t1.setText(d.getName());
- x=t1.getText();
- InputStream in=new FileInputStream(d);
- b=new byte[4096];
- in.read(b);
- y=new String(b).trim();
- z=x + " " + y;
- setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- }
- catch(Exception ae1)
- {
- ae1.printStackTrace();
- }
- }
- if(b2==o)
- {
- try
- {
- MessageDigest digest = MessageDigest.getInstance("MD5");
- byte[] inputBytes =y.getBytes();
- digest.update(inputBytes);
- byte[] hashBytes = digest.digest();
- hash=new String(hashBytes);
- System.out.println("Generated HashCode: - " + new String(hashBytes));
- OutputStream out=s.getOutputStream();
- out.write(z.trim().getBytes());
- out.write(hashBytes);
- System.out.println("File Sent");
- }
- catch(Exception ae)
- {
- ae.printStackTrace();
- }
- }
- }
- }
- Output :
- s
- PRACTICAL NO. 2
- Demonstrate techniques to create multi-level access control in databases.
- Method 1 : Using Separation
- Step 1 - Create a sample SQL Server table
- create table cust
- (
- CustId int Primary key not null,
- Name varchar(50) not null,
- AccNo varchar(10) not null,
- TypeOfAcc varchar(10) not null
- );
- Command(s) completed successfully.
- insert into cust values(1001,'Hina','S1001','Saving');
- (1 row(s) affected)
- insert into cust values(1002,'Siddhi','C2001','Current');
- (1 row(s) affected)
- insert into cust values(1003,'Shreyash','C2004','Current');
- (1 row(s) affected)
- insert into cust values(1004,'Shameena','C2007','Current');
- (1 row(s) affected)
- insert into cust values(1005,'Sanesh','S1004','Saving');
- (1 row(s) affected)
- Step 2 - Create a different views for different uses.
- create view saving_view
- as
- select CustId,Name from cust where TypeOfAcc='Saving';
- Command(s) completed successfully.
- create view current_view
- as
- select CustId,Name from cust where TypeOfAcc='Current';
- Command(s) completed successfully.
- select * from saving_view;
- select * from current_view;
- Method 2 : Encryption
- Step 1 - Create a sample SQL Server table
- create table cust
- (
- CustId int Primary key not null,
- Name varchar(50) not null,
- AccNo varchar(10) not null,
- TypeOfAcc varchar(10) not null
- );
- Command(s) completed successfully.
- insert into cust values(1001,'Hina','S1001','Saving');
- (1 row(s) affected)
- insert into cust values(1002,'Siddhi','C2001','Current');
- (1 row(s) affected)
- insert into cust values(1003,'Shreyash','C2004','Current');
- (1 row(s) affected)
- insert into cust values(1004,'Shameena','C2007','Current');
- (1 row(s) affected)
- insert into cust values(1005,'Sanesh','S1004','Saving');
- (1 row(s) affected)
- Step 2 - SQL Server Service Master Key
- USE master;
- GO
- SELECT *
- FROM sys.symmetric_keys
- WHERE name = '##MS_ServiceMasterKey##';
- GO
- Step 3 - SQL Server Database Master Key
- use hina;
- go
- create master key encryption by password='password123';
- go
- Command(s) completed successfully.
- Step 4 - Create a Self Signed SQL Server Certificate:
- use hina;
- go
- create certificate certificate1
- with subject='Protect Data';
- go
- Command(s) completed successfully.
- Step 5 - SQL Server Symmetric Key
- use hina;
- go
- create symmetric key symmetricKey1
- with algorithm=AES_128
- encryption by certificate certificate1;
- go
- Command(s) completed successfully.
- Step 6 - Schema changes
- use hina;
- go
- alter table cust
- add AccEncrypt varbinary(MAX) NULL;
- go
- Command(s) completed successfully.
- Step 7 - Encrypting the newly created column
- use hina;
- go
- OPEN SYMMETRIC KEY SymmetricKey1
- DECRYPTION BY CERTIFICATE Certificate1;
- GO
- UPDATE cust
- SET AccEncrypt = EncryptByKey (Key_GUID('SymmetricKey1'),AccNo)
- FROM cust;
- GO
- CLOSE SYMMETRIC KEY SymmetricKey1;
- GO
- (5 row(s) affected)
- Step 8 - Remove old column
- alter table cust
- drop column AccNo;
- Command(s) completed successfully.
- Step 9 - Reading the SQL Server Encrypted Data
- open symmetric key symmetricKey1
- decryption by certificate certificate1;
- select CustId,AccEncrypt as 'Encrypted Account No',
- convert(varchar,DECRYPTBYKEY(AccEncrypt)) as 'Decrypted Account No'
- from cust;
- close symmetric key symmetrickey1;
- Step 10 - Adding Records to the Table
- open symmetric key symmetricKey1
- decryption by certificate certificate1;
- insert into cust values (1006,'Tejas','Saving',ENCRYPTBYKEY(KEY_GUID('symmetricKey1'), CONVERT(varchar,'S1007')));
- (1 row(s) affected)r
- Step 11 - Accessing the Encrypted Data
- CREATE USER test1 WITHOUT LOGIN
- WITH DEFAULT_SCHEMA =dbo;
- grant select to test1;
- Command(s) completed successfully.
- execute as user='test1'
- select CustId,AccEncrypt as 'Encrypted Account No',
- convert(varchar,DECRYPTBYKEY(AccEncrypt)) as 'Decrypted Account No'
- from cust;
- Step 12 - Grant Permissions to the Encrypted Data
- GRANT VIEW DEFINITION ON SYMMETRIC KEY::SymmetricKey1 TO test;
- GRANT VIEW DEFINITION ON Certificate::Certificate1 TO test;
- Command(s) completed successfully.
- Method 3 : CHECKSUM
- create table tblUser
- (
- UserID INT IDENTITY(1,1) NOT NULL,
- LoginName NVARCHAR(40) NOT NULL,
- PasswordHash BINARY(64) NOT NULL,
- FirstName NVARCHAR(40) NULL,
- LastName NVARCHAR(40) NULL,
- CONSTRAINT [PK_User_UserID] PRIMARY KEY CLUSTERED (UserID ASC)
- )
- Command(s) completed successfully.
- CREATE PROCEDURE uspAddUser
- @pLogin NVARCHAR(50),
- @pPassword NVARCHAR(50),
- @pFirstName NVARCHAR(40) = NULL,
- @pLastName NVARCHAR(40) = NULL,
- @responseMessage NVARCHAR(250) OUTPUT
- AS
- BEGIN
- SET NOCOUNT ON
- BEGIN TRY
- INSERT INTO tblUser (LoginName, PasswordHash, FirstName, LastName)
- VALUES (@pLogin, HASHBYTES('MD2',@pPassword), @pFirstName, @pLastName)
- SET @responseMessage='Success'
- END TRY
- BEGIN CATCH
- SET @responseMessage=ERROR_MESSAGE()
- END CATCH
- END
- Command(s) completed successfully.
- DECLARE @responseMessage NVARCHAR(250)
- EXEC uspAddUser
- @pLogin = N'Admin',
- @pPassword = N'123',
- @pFirstName = N'Admin',
- @pLastName = N'Administrator',
- @responseMessage=@responseMessage
- OUTPUT
- Select * from tblUser;
- ALTER TABLE tblUser ADD Salt UNIQUEIDENTIFIER
- Command(s) completed successfully.
- ALTER PROCEDURE uspAddUser
- @pLogin NVARCHAR(50),
- @pPassword NVARCHAR(50),
- @pFirstName NVARCHAR(40) = NULL,
- @pLastName NVARCHAR(40) = NULL,
- @responseMessage NVARCHAR(250) OUTPUT
- AS
- BEGIN
- SET NOCOUNT ON
- DECLARE @salt UNIQUEIDENTIFIER
- SET @salt = NEWID()
- BEGIN TRY
- INSERT INTO tblUser (LoginName, PasswordHash, Salt, FirstName, LastName)
- VALUES(@pLogin, HASHBYTES('MD2', @pPassword+CAST(@salt AS NVARCHAR(36))), @salt, @pFirstName, @pLastName)
- SET @responseMessage='Success'
- END TRY
- BEGIN CATCH
- SET @responseMessage=ERROR_MESSAGE()
- END CATCH
- END
- Command(s) completed successfully.
- TRUNCATE TABLE tblUser
- Command(s) completed successfully.
- DECLARE @responseMessage NVARCHAR(250)
- EXEC uspAddUser
- @pLogin = N'Admin',
- @pPassword = N'123',
- @pFirstName = N'Admin',
- @pLastName = N'Administrator',
- @responseMessage=@responseMessage
- OUTPUT
- SELECT UserID, LoginName, PasswordHash, Salt, FirstName, LastName from tblUser
- CREATE PROCEDURE uspLogin
- @pLoginName NVARCHAR(254),
- @pPassword NVARCHAR(50),
- @responseMessage NVARCHAR(250)='' OUTPUT
- AS
- BEGIN
- SET NOCOUNT ON
- DECLARE @userID INT
- IF EXISTS (SELECT TOP 1 UserID FROM tblUser where LoginName=@pLoginName)
- BEGIN
- SET @userID = (SELECT UserID FROM tblUser WHERE LoginName = @pLoginName AND PasswordHash = HASHBYTES('MD2', @pPassword+CAST(Salt AS NVARCHAR(36))))
- IF(@UserID IS NULL)
- SET @responseMessage='Incorrect password'
- ELSE
- SET @responseMessage='User successfully logged in'
- END
- ELSE
- SET @responseMessage='Invalid login'
- END
- Command(s) completed successfully.
- DECLARE @responseMessage NVARCHAR(250)
- EXEC uspLogin
- @pLoginName = N'Admin',
- @pPassword = N'123',
- @responseMessage = @responseMessage
- OUTPUT
- SELECT @responseMessage as N'responseMessage'
- DECLARE @responseMessage NVARCHAR(250)
- EXEC uspLogin
- @pLoginName = N'Admin1',
- @pPassword = N'123',
- @responseMessage = @responseMessage
- OUTPUT
- SELECT @responseMessage as N'responseMessage'
- DECLARE @responseMessage NVARCHAR(250)
- EXEC uspLogin
- @pLoginName = N'Admin',
- @pPassword = N'12322',
- @responseMessage = @responseMessage
- OUTPUT
- SELECT @responseMessage as N'responseMessage'
- Method 4 : Single Cell Encryption
- Step 1 - Create a sample SQL Server table
- create table cust
- (
- CustId int Primary key not null,
- Name varchar(50) not null,
- AccNo varchar(10) not null,
- TypeOfAcc varchar(10) not null
- );
- Command(s) completed successfully.
- insert into cust values(1001,'Hina','S1001','Saving');
- (1 row(s) affected)
- insert into cust values(1002,'Siddhi','C2001','Current');
- (1 row(s) affected)
- insert into cust values(1003,'Shreyash','C2004','Current');
- (1 row(s) affected)
- insert into cust values(1004,'Shameena','C2007','Current');
- (1 row(s) affected)
- insert into cust values(1005,'Sanesh','S1004','Saving');
- (1 row(s) affected)
- Step 2 - SQL Server Service Master Key
- USE master;
- GO
- SELECT *
- FROM sys.symmetric_keys
- WHERE name = '##MS_ServiceMasterKey##';
- GO
- Step 3 - SQL Server Database Master Key
- use hina;
- go
- create master key encryption by password='password123';
- go
- Command(s) completed successfully.
- Step 4 - Create a Self Signed SQL Server Certificate:
- use hina;
- go
- create certificate certificate1
- with subject='Protect Data';
- go
- Command(s) completed successfully.
- Step 5 - SQL Server Symmetric Key
- use hina;
- go
- create symmetric key symmetricKey1
- with algorithm=AES_128
- encryption by certificate certificate1;
- go
- Command(s) completed successfully.
- Step 6 - Schema changes
- use hina;
- go
- alter table cust
- add AccNoEncrypt nvarchar(MAX) NULL;
- go
- Command(s) completed successfully.
- UPDATE cust
- SET AccNoEncrypt = EncryptByKey AccNo
- FROM cust;
- Command(s) completed successfully.
- Step 7 - Remove old column
- alter table cust
- drop column AccNo;
- insert into cust values (1006,'Tejas','Saving', 'S1007');
- Step 8 - Encrypting one cell
- open symmetric key symmetricKey1
- decryption by certificate certificate1;
- go
- update [db].[dbo].[cust]
- set AccNoEncrypt=ENCRYPTBYKEY(KEY_GUID('symmetricKey1'),'S1007')
- where CustId=1006;
- (1 row(s) affected)
- SELECT * FROM [db].[dbo].[cust]
- Method 5 : Row level Encryption
- Step 1 - Create a sample SQL Server table
- create table demo
- (
- Name nvarchar(MAX),
- AccNo nvarchar(MAX)
- );
- Command(s) completed successfully.
- insert into demo values('Hina','S1001');
- insert into demo values('Siddhi','C2001');
- insert into demo values('Shreyash','C2004');
- insert into demo values('Shameena','C2007');
- insert into demo values('Sanesh','S1004');
- Step 2 - SQL Server Service Master Key
- USE master;
- GO
- SELECT *
- FROM sys.symmetric_keys
- WHERE name = '##MS_ServiceMasterKey##';
- GO
- Step 3 - SQL Server Database Master Key
- use hina;
- go
- create master key encryption by password='password123';
- go
- Command(s) completed successfully.
- Step 4 - Create a Self Signed SQL Server Certificate:
- use hina;
- go
- create certificate certificate1
- with subject='Protect Data';
- go
- Command(s) completed successfully.
- Step 5 - SQL Server Symmetric Key
- use hina;
- go
- create symmetric key symmetricKey1
- with algorithm=AES_128
- encryption by certificate certificate1;
- go
- Command(s) completed successfully.
- Step 6 - Inserting Encrypted Values
- open symmetric key symmetricKey1
- decryption by certificate certificate1;
- insert into demo values (ENCRYPTBYKEY(KEY_GUID('symmetricKey1'),'Tejas'),ENCRYPTBYKEY(KEY_GUID('symmetricKey1'),'S1007'));
- (1 row(s) affected)
- select * from demo
- PRACTICAL NO. 3
- Aim : Create a honeypot and demonstrate the following –
- a) Penetration
- b) Phishing
- Description:- Ping Flood Attack
- How to Perform:-
- Step 1:-
- Detect Target Address through Zenmap using starting adress of IP adress and mask adress
- e.g. Here I am targeting IP address 192.168.2.190
- Step 2:-
- Ping to target machine as follow:-
- Detection:-
- Step 1:-
- Search for ICMP
- Step 2:-
- Go to Statistic==>Endpoints
- Find length of Packet
- Step 3:-
- Get location from LAN IP address as follows:-
- 2)Brute force attack
- Software used: Cain and able
- Step: 1) Open cain and able. Click on Start/Stop sniffer. Click on + sign and add the ip of the network.
- Step: 2)Click on the APR tab at the bottom of the screen. Click on + sign. Select the ip and add. Click the APR symbol on the top left of the screen and Poisoning will start.
- Step: 3) Open a browser and visit any Not Secured website. Enter the user id and password and submit.
- Step: 4) Click on the passwords tab at the bottom of the screen. Click on HttP and the passwords will be displayed.
- 3 ) ARP Flooding:
- Software Used: Colasoft
- Open Colasoft.
- Check the network adapter for connection.
- Click on add in the top left corner of the screen.
- Select the ARP Packet. Let time be default.
- Click Ok and proceed.
- Now enter the mac and ip address of the source and destination where necessary.
- Now select the packet in the Packet list. Right Click on the packet and click on send selected packets.
- Select the adapter and insert the values. Then Click start.
- ARP packets will start broadcasting.
- Now Trace the network with wireshark on the destination machine.
- The network is flooded with ARP packets originating from the source machine.
- PRACTICAL NO. 4
- Aim : Configure and implement SSL/TSL for any webpages to maintain secure session communication.
- EchoServer.java
- import javax.net.ssl.*;
- import java.io.*;
- public class EchoServer
- {
- public static void main(String[] arstring)
- {
- try
- {
- SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
- SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
- SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
- InputStream is = sslSocket.getInputStream();
- InputStreamReader isReader = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isReader);
- String string = null;
- while ((string = br.readLine()) != null)
- {
- System.out.println(string);
- System.out.flush();
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- EchoClient.java
- import javax.net.ssl.*;
- import java.io.*;
- public class EchoClient
- {
- public static void main(String[] arstring)
- {
- try
- {
- SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
- InputStream is = System.in;
- InputStreamReader isReader = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isReader);
- OutputStream os = sslSocket.getOutputStream();
- OutputStreamWriter osWriter = new OutputStreamWriter(os);
- BufferedWriter bw = new BufferedWriter(osWriter);
- String string = null;
- while ((string = br.readLine()) != null)
- {
- bw.write(string + '\n');
- bw.flush();
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- Output :
- PRACTICAL NO. 5
- Aim : Write a program to send an encrypted Email which allows the user to choose the type of encryption. Implement any 3 techniques.
- Code: -
- package encryptmail;
- import com.sun.mail.util.BASE64EncoderStream;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.util.Properties;
- import java.util.Scanner;
- import javax.crypto.*;
- import javax.mail.*;
- import javax.mail.internet.*;
- import sun.misc.BASE64Encoder;
- public class EncryptMail
- {
- public static void main(String[] args)
- {
- Scanner sc=new Scanner(System.in);
- System.out.println("Choose the Algorithm for email encryption\n1.AES\n2.DES\n3.RSA");
- intalgoN=sc.nextInt();
- String algo="null";
- if(algoN==1)
- {
- algo="AES";
- }
- if(algoN==2)
- {
- algo="DES";
- }
- if(algoN==3)
- {
- algo="RSA";
- }
- String to="adityasahastrabudhe97@gmail.com";
- Properties props = new Properties();
- props.put("mail.smtp.starttls.enable","true");
- props.put("mail.smtp.host", "smtp.gmail.com");
- props.put("mail.smtp.ssl.trust","smtp.gmail.com");
- props.put("mail.smtp.socketFactory.port", "465");
- props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.port", "465");
- Session session = Session.getDefaultInstance(props,newjavax.mail.Authenticator()
- {
- protected PasswordAuthenticationgetPasswordAuthentication()
- {
- return new PasswordAuthentication("adityasahastrabudhe97@gmail.com","123");
- }
- });
- try
- {
- String cipherText="",decryptedText;
- String msg="hello";
- if(algo.equals("AES"))
- {
- KeyGeneratorkeyGen=KeyGenerator.getInstance(algo);
- keyGen.init(128);
- SecretKeysecretKey=keyGen.generateKey();
- Cipher aesCipher=Cipher.getInstance(algo);
- aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
- byte[] byteDataToEncrypt=msg.getBytes();
- byte[] byteCipherText=aesCipher.doFinal(byteDataToEncrypt);
- cipherText=new BASE64Encoder().encode(byteCipherText);
- }
- if(algo.equals("RSA"))
- {
- final intkeySize = 2048;
- KeyPairGeneratorkeyPairGenerator = KeyPairGenerator.getInstance("RSA");
- keyPairGenerator.initialize(keySize);
- KeyPairkeyPair = keyPairGenerator.genKeyPair();
- PublicKeypubKey = keyPair.getPublic();
- PrivateKeyprivateKey = keyPair.getPrivate();
- Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
- byte [] encrypted = cipher.doFinal(msg.getBytes());
- cipherText=new String(encrypted);
- }
- if(algo.equals("DES"))
- {
- SecretKey key;
- Cipher ecipher;
- key = KeyGenerator.getInstance("DES").generateKey();
- ecipher = Cipher.getInstance("DES");
- ecipher.init(Cipher.ENCRYPT_MODE, key);
- byte[] utf8 = msg.getBytes("UTF8");
- byte[] enc = ecipher.doFinal(utf8);
- enc = BASE64EncoderStream.encode(enc);
- cipherText= new String(enc);
- }
- MimeMessage message = new MimeMessage(session);
- message.setFrom(new InternetAddress("adityasahastrabudhe97@gmail.com"));
- message.addRecipient(Message.RecipientType.TO,newInternetAddress(to));
- message.setSubject("Hello");
- message.setText(cipherText);
- Transport.send(message);
- System.out.println("message sent successfully");
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- Output: -
- Choose the Algorithm for email encryption
- 1.AES
- 2.DES
- 3.RSA
- 1
- message sent successfully.
- PRACTICAL NO. 6
- Aim : Implement ESX file system security in cloud.
- Prerequisites
- To run this quickstart, you'll need:
- • Python 2.6 or greater.
- • The pip package management tool.
- • A Google account with Google Drive enabled.
- Step 1: Turn on the Drive API
- a. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
- b. On the Add credentials to your project page, click the Cancel button.
- c. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
- d. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
- e. Select the application type Other, enter the name "Drive API Quickstart", and click the Create button.
- f. Click OK to dismiss the resulting dialog.
- g. Click the file_download (Download JSON) button to the right of the client ID.
- h. Move this file to your working directory and rename it client_secret.json.
- Step 2: Install the Google Client Library
- Run the following command to install the library using pip:
- pip install --upgrade google-api-python-client
- See the library's installation page for the alternative installation options.
- Step 3: Copy paste the bellow code in another file and execute the file using :
- python filename
- Code:
- from __future__ import print_function
- import httplib2
- import os
- import random
- from apiclient import discovery
- from apiclient.http import MediaFileUpload
- from oauth2client import client
- from oauth2client import tools
- from oauth2client.file import Storage
- from Crypto.Cipher import AES
- from Crypto.Hash import SHA256
- try:
- import argparse
- flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
- except ImportError:
- flags = None
- SCOPES = 'https://www.googleapis.com/auth/drive'
- CLIENT_SECRET_FILE = 'client_secret.json'
- APPLICATION_NAME = 'Drive API Python Quickstart'
- def get_credentials():
- # checks if credentials are present. if not creates new dir and stores credentials in it.
- # creates dir if dir is not present.
- credential_dir = os.path.join(os.getcwd(), '.credentials')
- if not os.path.exists(credential_dir):
- os.makedirs(credential_dir)
- credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json')
- # gets credentials
- store = Storage(credential_path)
- credentials = store.get()
- # if credentials not found, creates credentials by receiving authorization from user using authentication flow and stores in cwd
- if not credentials or credentials.invalid:
- flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
- flow.user_agent = APPLICATION_NAME
- if flags:
- credentials = tools.run_flow(flow, store, flags)
- else: # Needed only for compatibility with Python 2.6
- credentials = tools.run(flow, store)
- print('Storing credentials to ' + credential_path)
- return credentials
- def get_service():
- credentials = get_credentials()
- http = credentials.authorize(httplib2.Http())
- drive_service = discovery.build('drive', 'v3', http=http)
- return drive_service
- def get_key(password):
- # creates SHA256 hash of the password
- password = password.encode('ascii')
- hasher = SHA256.new(password)
- return hasher.digest()
- def encrypt_file(file_name, key):
- # encrypts the file with the provided key using AES-128
- chuncksize = 64 * 1024
- outputfilename = file_name + ".enc"
- filesize = str(os.path.getsize(file_name)).zfill(16)
- IV = ''
- for i in range(16):
- IV += chr(random.randint(97, 123))
- IV = IV.encode('ascii')
- encryptor = AES.new(key, AES.MODE_CBC, IV)
- with open(file_name, 'rb') as infile:
- with open(outputfilename, 'wb') as outfile:
- outfile.write(filesize.encode('ascii'))
- outfile.write(IV)
- while True:
- chunck = infile.read(chuncksize)
- if(len(chunck) == 0):
- break
- if(len(chunck) % 16 != 0):
- chunck += (' ' * (16 - len(chunck) % 16)).encode('ascii')
- outfile.write(encryptor.encrypt(chunck))
- return outputfilename
- def upload_file(drive_service, filename, filepath):
- file_metadata = {'name': filename}
- media = MediaFileUpload(filepath)
- file = drive_service.files().create(body=file_metadata,
- media_body=media, fields='id').execute()
- print('File ID: %s' % file.get('id'))
- def main():
- drive_service = get_service()
- file_name = input("Name of the file you want to encrypt and upload: ")
- password = input("Enter the password to encrypt the file: ")
- print("Encrypting file...")
- encrypted_file = encrypt_file(file_name, get_key(password))
- print("Uploading encrypted file...")
- upload_file(drive_service, encrypted_file, encrypted_file)
- print("File uploaded succesfully.")
- if __name__ == '__main__':
- main()
- PRACTICAL NO. 7
- PRACTICAL NO.7: Write a program to generate DSA SSH key.
- Export.java
- import java.io.*;
- importjava.security.*;
- importjava.security.spec.DSAPrivateKeySpec;
- public class Export
- {
- public static void main(String args[])
- {
- try
- {
- KeyPairGeneratorkpg = KeyPairGenerator.getInstance("DSA");
- SecureRandomrnd = SecureRandom.getInstance("SHA1PRNG","SUN");
- kpg.initialize(1024,rnd);
- KeyPairkp = kpg.generateKeyPair();
- Class spec = Class.forName("java.security.spec.DSAPrivateKeySpec");
- KeyFactorykf = KeyFactory.getInstance("DSA");
- DSAPrivateKeySpecks = (DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(), spec);
- FileOutputStreamfos = new FileOutputStream("ExportedKey.txt");
- ObjectOutputStreamoos = new ObjectOutputStream(fos);
- oos.writeObject(ks.getX());
- oos.writeObject(ks.getP());
- oos.writeObject(ks.getQ());
- oos.writeObject(ks.getG());
- System.out.println("Private Key Exported");
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- OUTPUT:
- Import.java
- import java.io.*;
- importjava.math.BigInteger;
- importjava.security.*;
- importjava.security.spec.DSAPrivateKeySpec;
- public class Import
- {
- public static void main(String args[])
- {
- try
- {
- FileInputStreamfis = new FileInputStream("exportedKey.txt");
- ObjectInputStreamois = new ObjectInputStream(fis);
- DSAPrivateKeySpecks = new DSAPrivateKeySpec((BigInteger)ois.readObject(),(BigInteger)ois.readObject(),(BigInteger)ois.readObject(),(BigInteger)ois.readObject());
- KeyFactorykf = KeyFactory.getInstance("DSA");
- PrivateKeypk = kf.generatePrivate(ks);
- System.out.println("Got private key.");
- }
- catch(FileNotFoundException e)
- {
- System.out.println("Key not found.");
- }
- catch(Exception e)
- {
- System.out.println("Key is corrupted.");
- }
- }
- }
- OUTPUT:
- PRACTICAL NO. 8
- Demonstrate and implement Bluetooth security.
- Requirements
- 1. pc with bluetooth
- 2. python lightblue package
- 3. python version 2.7
- 4. target device needs to be paired with the host device
- Command to install lightblue package
- sudo apt-get install python-lightblue --(internet required)
- Code :
- import bluetooth
- import lightblue
- import os
- import random
- from Crypto.Cipher import AES
- from Crypto.Hash import SHA256
- def get_nearby_devices():
- #searches for nearby devices
- print "searching for nearby devices..."
- nearby_devices = bluetooth.discover_devices()
- return nearby_devices
- def is_target_on(nearby_devices,target_name):
- #checks if target is on
- for bdaddr in nearby_devices:
- print bluetooth.lookup_name(bdaddr)
- if target_name == bluetooth.lookup_name(bdaddr):
- print "found the target device!"
- target_address = bdaddr
- print"Target Address: " + target_address
- return target_address
- return None
- def get_services(target_address):
- #gets the list of all services the target provides over bluetooth
- print "searching for the object push service..."
- services = lightblue.findservices(target_address)
- print services
- def get_key(password):
- # creates SHA256 hash of the password
- hasher = SHA256.new(password)
- return hasher.digest()
- def encrypt_file(file_name, key):
- # encrypts the file with the provided key using AES-128
- chuncksize = 64*1024
- outputfile = file_name +".enc"
- filesize = str(os.path.getsize(file_name)).zfill(16)
- IV = ''
- for i in range(16):
- IV += chr(random.randint(0,0xFF))
- encryptor = AES.new(key, AES.MODE_CBC, IV)
- with open(file_name, 'rb') as infile:
- with open(outputfile, 'wb') as outfile:
- outfile.write(filesize)
- outfile.write(IV)
- while True:
- chunck = infile.read(chuncksize)
- if(len(chunck) == 0):
- break
- if(len(chunck) % 16 != 0):
- chunck += ' ' * (16 - len(chunck)%16)
- outfile.write(encryptor.encrypt(chunck))
- outfile.close()
- return outputfile
- if __name__ == '__main__':
- # we should know
- file_name = raw_input("Enter the name of the file you want to send: ")
- password = raw_input("Enter password to encrypt file: ")
- file_to_send = encrypt_file(file_name, get_key(password))
- # we don't know yet
- obex_port = None
- target_address = None
- nearby_devices = get_nearby_devices()
- devices = []
- for mac in nearby_devices:
- print bluetooth.lookup_name(mac)
- devices.append(mac)
- target_index = int(raw_input("Enter the index of device: "))
- target_address = devices[target_index]
- # target_address = is_target_on(nearby_devices,target_name)
- get_services(target_address)
- obex_port = int(raw_input("Enter the obex port: "))
- print "sending a file..."
- lightblue.obex.sendfile(target_address, obex_port, file_to_send)
- print "File sent."
- PRACTICAL NO. 9
- Develop application to implement Zigbee security.
- • Open Xctu application
- • Click on the discover devices.
- • Next the discoverable window will be start.
- • Select the device connected to the the xctu.
- • Then Click next.
- • Do not change the parameters in the next window.
- • Click on finish button.
- Let the application load the module
- After it detects the module press add selected device.
- • After clickingon the add slected this the main window will start with the decice name and the amc address.
- • Doublic click on it to open the properties of it in the right pane of the application.
- • Change the pan id according to your need.
- • Write the changes by clicking the write button.
- • After write the changes click on the console button on the application bar to open the console window.
- • Press the open button to create a connection with the other zigbee.
- • Type any msg in the console and it display it on the consooe of other zigbee.
- Sending Code
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(9600);
- }
- void loop() {
- // put your main code here, to run repeatedly:
- Serial.print("Hello World");
- delay(5000);
- }
- Receive Code
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(9600);
- }
- void loop() {
- // put your main code here, to run repeatedly:
- if(Serial.available()>0)
- {
- Serial.write(Serial.read());
- }
- }
Add Comment
Please, Sign In to add comment