· 7 years ago · Apr 24, 2018, 04:06 AM
1PRACTICAL NO. 1
2 Demonstrate techniques for file and data integrity.
3Data Integrity :
4User1.java
5import java.net.*;
6import java.io.*;
7import java.util.*;
8import java.io.UnsupportedEncodingException;
9import java.security.MessageDigest;
10import java.security.NoSuchAlgorithmException;
11import java.util.Arrays;
12import java.util.Base64;
13import javax.crypto.Cipher;
14import javax.crypto.spec.SecretKeySpec;
15class User1
16{
17 DatagramSocket d;
18 DatagramPacket p,p1;
19 int i=0;
20 private static SecretKeySpec secretKey;
21 private static byte[] key;
22 final String Keys = "ssshhhhhhhhhhh!!!!";
23 User1()
24 {
25 try
26 {
27 d=new DatagramSocket(1000);
28 for(i=0;i<20;i++)
29 {
30
31 System.out.println("Enter a msg");
32 Scanner sc=new Scanner(System.in);
33 String msg=sc.next();
34
35 String encryptedString = User1.encrypt(msg,Keys) ;
36 p=new DatagramPacket(encryptedString.getBytes(),encryptedString.length(),InetAddress.getLocalHost(),2000);
37 d.send(p);
38 System.out.println("Encrypted Msg "+encryptedString);
39 System.out.println("msg sent");
40 receive();
41 }
42 }
43 catch(Exception e)
44 {
45 e.printStackTrace();
46 }
47
48 }
49 public void receive()
50 {
51 try
52 {
53 byte b[]=new byte[1024];
54 p1=new DatagramPacket(b,b.length);
55 d.receive(p1);
56 String s=new String(p1.getData());
57 String decryptedString = User1.decrypt(s.trim(),Keys) ;
58
59 System.out.println(decryptedString);
60 System.out.println(s.trim());
61 }
62 catch(Exception ex)
63 {
64 ex.printStackTrace();
65 }
66 }
67
68 public static void setKey(String myKey)
69 {
70 MessageDigest sha = null;
71 try {
72 key = myKey.getBytes("UTF-8");
73 sha = MessageDigest.getInstance("SHA-1");
74 key = sha.digest(key);
75 key = Arrays.copyOf(key, 16);
76 secretKey = new SecretKeySpec(key, "AES");
77 }
78 catch (NoSuchAlgorithmException e) {
79 e.printStackTrace();
80 }
81 catch (UnsupportedEncodingException e) {
82 e.printStackTrace();
83 }
84 }
85
86 public static String encrypt(String strToEncrypt, String secret)
87 {
88 try
89 {
90 setKey(secret);
91 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
92 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
93 return Base64.getEncoder().withoutPadding().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
94 }
95 catch (Exception e)
96 {
97 System.out.println("Error while encrypting: " + e.toString());
98 }
99 return null;
100 }
101
102 public static String decrypt(String strToDecrypt, String secret)
103 {
104 try
105 {
106 setKey(secret);
107 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
108 cipher.init(Cipher.DECRYPT_MODE, secretKey);
109 return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
110 }
111 catch (Exception e)
112 {
113 System.out.println("Error while decrypting: " + e.toString());
114 }
115 return null;
116 }
117 public static void main(String s[])
118 {
119 new User1();
120 }
121}
122
123User2.java
124import java.net.*;
125import java.io.*;
126import java.util.*;
127import java.net.*;
128import java.io.*;
129import java.util.*;
130import java.io.UnsupportedEncodingException;
131import java.security.MessageDigest;
132import java.security.NoSuchAlgorithmException;
133import java.util.Arrays;
134import java.util.Base64;
135import javax.crypto.Cipher;
136import javax.crypto.spec.SecretKeySpec;class User2
137{
138 DatagramSocket d;
139 DatagramPacket p,p1;
140 int i=0;
141 private static SecretKeySpec secretKey;
142 private static byte[] key;
143 final String Keys = "ssshhhhhhhhhhh!!!!";
144
145 User2()
146 {
147 try
148 {
149 d=new DatagramSocket(2000);
150 for(i=0;i<20;i++)
151 {
152 byte b[]=new byte[1024];
153 p1=new DatagramPacket(b,b.length);
154 d.receive(p1);
155 String s=new String(p1.getData());
156 //byte[]text=s.getBytes();
157
158 System.out.println(s.trim());
159 String decryptedString = User2.decrypt(s.trim(),Keys) ;
160
161 System.out.println(decryptedString);
162
163 send();
164 }
165 }
166 catch(Exception e)
167 {
168 e.printStackTrace();
169 }
170
171 }
172 public void send()
173 {
174 try
175 {
176 System.out.println("Enter a msg");
177 Scanner sc=new Scanner(System.in);
178 String msg=sc.next();
179 String encryptedString = User2.encrypt(msg,Keys) ;
180 p=new DatagramPacket(encryptedString.getBytes(),encryptedString.length(),InetAddress.getLocalHost(),2000);
181 d.send(p);
182 System.out.println("Encrypted Msg "+encryptedString);
183 System.out.println("msg sent");
184 }
185 catch(Exception ex)
186 {
187 ex.printStackTrace();
188 }
189 }
190 public static void setKey(String myKey)
191 {
192 MessageDigest sha = null;
193 try {
194 key = myKey.getBytes("UTF-8");
195 sha = MessageDigest.getInstance("SHA-1");
196 key = sha.digest(key);
197 key = Arrays.copyOf(key, 16);
198
199 secretKey = new SecretKeySpec(key, "AES");
200 }
201 catch (NoSuchAlgorithmException e) {
202 e.printStackTrace();
203 }
204 catch (UnsupportedEncodingException e) {
205 e.printStackTrace();
206 }
207 }
208
209 public static String encrypt(String strToEncrypt, String secret)
210 {
211 try
212 {
213 setKey(secret);
214 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
215 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
216 return Base64.getEncoder().withoutPadding().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
217 }
218 catch (Exception e)
219 {
220 System.out.println("Error while encrypting: " + e.toString());
221 }
222 return null;
223 }
224 public static String decrypt(String strToDecrypt, String secret)
225 {
226 try
227 {
228 setKey(secret);
229 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
230 cipher.init(Cipher.DECRYPT_MODE, secretKey);
231 return new String(cipher.doFinal(Base64.getMimeDecoder().decode(strToDecrypt)));
232 }
233 catch (Exception e)
234 {
235 System.out.println("Error while decrypting: " + e.toString());
236 }
237 return null;
238 }
239 public static void main(String s[])
240 {
241 new User2();
242 }
243}
244
245Output :
246
247
248
249
250File Integrity :
251Server.java
252import java.util.*;
253import javax.swing.*;
254import java.awt.*;
255import javax.swing.*;
256import java.awt.*;
257import java.awt.event.*;
258import java.net.*;
259import java.io.*;
260import java.util.*;
261import java.security.*;
262
263class Server extends JFrame implements ActionListener
264{
265 JLabel l1;
266 JTextField t1;
267 JTextArea ta;
268 JButton b1,b2,b3;
269 Socket s;
270 ServerSocket ss;
271 String z,x,y,hash;
272 String m[];
273 JScrollPane scroll;
274 Server()
275 {
276 super("Server");
277 try
278 {
279 ss=new ServerSocket(1000);
280 s=ss.accept();
281 l1=new JLabel("File Name:- ");
282 t1=new JTextField(20);
283 ta=new JTextArea(20,30);
284 scroll = new JScrollPane(ta);
285 b2=new JButton("Open");
286 b3=new JButton("Check Integrity");
287 setLayout(new FlowLayout());
288 add(l1);
289 add(t1);
290 add(b2);
291 add(b3);
292 add(scroll);
293 setSize(600,600);
294 setVisible(true);
295 b2.addActionListener(this);
296 b3.addActionListener(this);
297 InputStream in=s.getInputStream();
298 InputStream in2=s.getInputStream();
299 byte b[]=new byte[4096];
300 byte b2[]=new byte[1024];
301 in.read(b);
302 in2.read(b2);
303 String msg=new String(b);
304 String h=new String(b2);
305 m=msg.trim().split(" ");
306 System.out.println(m[0]);
307 System.out.println(h);
308 t1.setText(m[0]);
309 hash=h.trim();
310 System.out.println("Generated Hash:-" + hash);
311 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
312 }
313 catch(Exception e)
314 {
315 e.printStackTrace();
316 }
317
318 }
319 public static void main(String args[])
320 {
321 new Server();
322 }
323 public void actionPerformed(ActionEvent e)
324 {
325 Object o=e.getSource();
326 if(b2==o)
327 {
328 for(int i=1;i<m.length;i++)
329 ta.append(m[i] + " ");
330 }
331 if(b3==o)
332 {
333 try
334 {
335 MessageDigest digest = MessageDigest.getInstance("MD5");
336 byte[] inputBytes =ta.getText().trim().getBytes();
337 digest.update(inputBytes);
338 byte[] hashBytes = digest.digest();
339 System.out.println("Calculated HashCode: - " + new String(hashBytes));
340 if(hash.equals(new String(hashBytes)))
341 {
342 System.out.println("File Integrity is maintained");
343 }
344 else
345 {
346 System.out.println("File Integrity is not maintained");
347 }
348 }
349 catch(Exception e1)
350 {
351 e1.printStackTrace();
352 }
353 }
354 }
355}
356Client.java
357import java.util.*;
358import javax.swing.*;
359import java.awt.*;
360import javax.swing.*;
361import java.awt.*;
362import java.awt.event.*;
363import java.net.*;
364import java.io.*;
365import java.util.*;
366import java.security.*;
367
368class Client extends JFrame implements ActionListener
369{
370 JLabel l1;
371 JTextField t1;
372 JTextArea ta;
373 JButton b1,b2;
374 Socket s;
375 String z,x,y,hash;
376 byte b[];
377
378 Client()
379 {
380 super("Client");
381 try
382 {
383 s=new Socket(InetAddress.getByName("localhost"),1000);
384 b1=new JButton("browse");
385 t1=new JTextField(20);
386 b2=new JButton("send");
387 setLayout(new FlowLayout());
388 add(b1);
389 add(t1);
390 add(b2);
391 setSize(400,400);
392 setVisible(true);
393 b1.addActionListener(this);
394 b2.addActionListener(this);
395 }
396 catch(Exception e)
397 {
398 e.printStackTrace();
399
400 }
401 }
402 public static void main(String args[])
403 {
404 new Client();
405 }
406 public void actionPerformed(ActionEvent e)
407 {
408 Object o=e.getSource();
409 if(b1==o)
410 {
411 try
412 {
413 JFileChooser f=new JFileChooser();
414 f.showOpenDialog(null);
415 File d=f.getSelectedFile();
416 t1.setText(d.getName());
417 x=t1.getText();
418 InputStream in=new FileInputStream(d);
419 b=new byte[4096];
420 in.read(b);
421 y=new String(b).trim();
422 z=x + " " + y;
423 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
424 }
425 catch(Exception ae1)
426 {
427 ae1.printStackTrace();
428 }
429 }
430 if(b2==o)
431 {
432 try
433 {
434 MessageDigest digest = MessageDigest.getInstance("MD5");
435 byte[] inputBytes =y.getBytes();
436 digest.update(inputBytes);
437 byte[] hashBytes = digest.digest();
438 hash=new String(hashBytes);
439
440 System.out.println("Generated HashCode: - " + new String(hashBytes));
441 OutputStream out=s.getOutputStream();
442 out.write(z.trim().getBytes());
443 out.write(hashBytes);
444
445 System.out.println("File Sent");
446 }
447 catch(Exception ae)
448 {
449 ae.printStackTrace();
450 }
451 }
452 }
453}
454
455Output :
456
457s
458
459 
460PRACTICAL NO. 2
461Demonstrate techniques to create multi-level access control in databases.
462Method 1 : Using Separation
463Step 1 - Create a sample SQL Server table
464create table cust
465(
466 CustId int Primary key not null,
467 Name varchar(50) not null,
468 AccNo varchar(10) not null,
469 TypeOfAcc varchar(10) not null
470);
471
472Command(s) completed successfully.
473
474
475insert into cust values(1001,'Hina','S1001','Saving');
476(1 row(s) affected)
477
478
479insert into cust values(1002,'Siddhi','C2001','Current');
480(1 row(s) affected)
481
482insert into cust values(1003,'Shreyash','C2004','Current');
483(1 row(s) affected)
484
485insert into cust values(1004,'Shameena','C2007','Current');
486(1 row(s) affected)
487
488insert into cust values(1005,'Sanesh','S1004','Saving');
489(1 row(s) affected)
490
491Step 2 - Create a different views for different uses.
492
493create view saving_view
494as
495select CustId,Name from cust where TypeOfAcc='Saving';
496Command(s) completed successfully.
497
498
499create view current_view
500as
501select CustId,Name from cust where TypeOfAcc='Current';
502Command(s) completed successfully.
503
504
505
506
507select * from saving_view;
508
509
510
511select * from current_view;
512
513
514
515Method 2 : Encryption
516Step 1 - Create a sample SQL Server table
517create table cust
518(
519 CustId int Primary key not null,
520 Name varchar(50) not null,
521 AccNo varchar(10) not null,
522 TypeOfAcc varchar(10) not null
523);
524
525Command(s) completed successfully.
526
527
528insert into cust values(1001,'Hina','S1001','Saving');
529(1 row(s) affected)
530
531
532insert into cust values(1002,'Siddhi','C2001','Current');
533(1 row(s) affected)
534
535insert into cust values(1003,'Shreyash','C2004','Current');
536(1 row(s) affected)
537
538insert into cust values(1004,'Shameena','C2007','Current');
539(1 row(s) affected)
540
541insert into cust values(1005,'Sanesh','S1004','Saving');
542(1 row(s) affected)
543Step 2 - SQL Server Service Master Key
544
545USE master;
546GO
547SELECT *
548FROM sys.symmetric_keys
549WHERE name = '##MS_ServiceMasterKey##';
550GO
551
552
553
554Step 3 - SQL Server Database Master Key
555use hina;
556go
557create master key encryption by password='password123';
558go
559
560Command(s) completed successfully.
561
562Step 4 - Create a Self Signed SQL Server Certificate:
563
564use hina;
565go
566create certificate certificate1
567with subject='Protect Data';
568go
569
570Command(s) completed successfully.
571
572
573Step 5 - SQL Server Symmetric Key
574use hina;
575go
576create symmetric key symmetricKey1
577with algorithm=AES_128
578encryption by certificate certificate1;
579go
580
581Command(s) completed successfully.
582
583
584
585Step 6 - Schema changes
586use hina;
587go
588alter table cust
589add AccEncrypt varbinary(MAX) NULL;
590go
591
592Command(s) completed successfully.
593
594Step 7 - Encrypting the newly created column
595use hina;
596go
597OPEN SYMMETRIC KEY SymmetricKey1
598DECRYPTION BY CERTIFICATE Certificate1;
599GO
600UPDATE cust
601SET AccEncrypt = EncryptByKey (Key_GUID('SymmetricKey1'),AccNo)
602FROM cust;
603GO
604CLOSE SYMMETRIC KEY SymmetricKey1;
605GO
606
607
608(5 row(s) affected)
609
610
611Step 8 - Remove old column
612alter table cust
613drop column AccNo;
614
615Command(s) completed successfully.
616
617
618
619Step 9 - Reading the SQL Server Encrypted Data
620open symmetric key symmetricKey1
621decryption by certificate certificate1;
622
623select CustId,AccEncrypt as 'Encrypted Account No',
624 convert(varchar,DECRYPTBYKEY(AccEncrypt)) as 'Decrypted Account No'
625 from cust;
626
627 close symmetric key symmetrickey1;
628
629
630
631Step 10 - Adding Records to the Table
632open symmetric key symmetricKey1
633decryption by certificate certificate1;
634
635insert into cust values (1006,'Tejas','Saving',ENCRYPTBYKEY(KEY_GUID('symmetricKey1'), CONVERT(varchar,'S1007')));
636
637(1 row(s) affected)r
638
639Step 11 - Accessing the Encrypted Data
640
641CREATE USER test1 WITHOUT LOGIN
642WITH DEFAULT_SCHEMA =dbo;
643
644grant select to test1;
645
646Command(s) completed successfully.
647
648execute as user='test1'
649select CustId,AccEncrypt as 'Encrypted Account No',
650 convert(varchar,DECRYPTBYKEY(AccEncrypt)) as 'Decrypted Account No'
651 from cust;
652
653Step 12 - Grant Permissions to the Encrypted Data
654GRANT VIEW DEFINITION ON SYMMETRIC KEY::SymmetricKey1 TO test;
655GRANT VIEW DEFINITION ON Certificate::Certificate1 TO test;
656
657Command(s) completed successfully.
658
659Method 3 : CHECKSUM
660
661create table tblUser
662(
663UserID INT IDENTITY(1,1) NOT NULL,
664LoginName NVARCHAR(40) NOT NULL,
665PasswordHash BINARY(64) NOT NULL,
666FirstName NVARCHAR(40) NULL,
667LastName NVARCHAR(40) NULL,
668CONSTRAINT [PK_User_UserID] PRIMARY KEY CLUSTERED (UserID ASC)
669)
670
671Command(s) completed successfully.
672
673
674CREATE PROCEDURE uspAddUser
675 @pLogin NVARCHAR(50),
676 @pPassword NVARCHAR(50),
677 @pFirstName NVARCHAR(40) = NULL,
678 @pLastName NVARCHAR(40) = NULL,
679 @responseMessage NVARCHAR(250) OUTPUT
680AS
681BEGIN
682 SET NOCOUNT ON
683 BEGIN TRY
684 INSERT INTO tblUser (LoginName, PasswordHash, FirstName, LastName)
685 VALUES (@pLogin, HASHBYTES('MD2',@pPassword), @pFirstName, @pLastName)
686
687 SET @responseMessage='Success'
688 END TRY
689
690 BEGIN CATCH
691 SET @responseMessage=ERROR_MESSAGE()
692 END CATCH
693END
694
695Command(s) completed successfully.
696
697
698DECLARE @responseMessage NVARCHAR(250)
699EXEC uspAddUser
700 @pLogin = N'Admin',
701 @pPassword = N'123',
702 @pFirstName = N'Admin',
703 @pLastName = N'Administrator',
704 @responseMessage=@responseMessage
705OUTPUT
706Select * from tblUser;
707
708
709
710
711ALTER TABLE tblUser ADD Salt UNIQUEIDENTIFIER
712
713
714Command(s) completed successfully.
715
716
717ALTER PROCEDURE uspAddUser
718 @pLogin NVARCHAR(50),
719 @pPassword NVARCHAR(50),
720 @pFirstName NVARCHAR(40) = NULL,
721 @pLastName NVARCHAR(40) = NULL,
722 @responseMessage NVARCHAR(250) OUTPUT
723AS
724BEGIN
725 SET NOCOUNT ON
726
727 DECLARE @salt UNIQUEIDENTIFIER
728 SET @salt = NEWID()
729 BEGIN TRY
730 INSERT INTO tblUser (LoginName, PasswordHash, Salt, FirstName, LastName)
731 VALUES(@pLogin, HASHBYTES('MD2', @pPassword+CAST(@salt AS NVARCHAR(36))), @salt, @pFirstName, @pLastName)
732
733 SET @responseMessage='Success'
734 END TRY
735
736 BEGIN CATCH
737 SET @responseMessage=ERROR_MESSAGE()
738 END CATCH
739END
740
741Command(s) completed successfully.
742
743
744TRUNCATE TABLE tblUser
745
746Command(s) completed successfully.
747
748DECLARE @responseMessage NVARCHAR(250)
749EXEC uspAddUser
750 @pLogin = N'Admin',
751 @pPassword = N'123',
752 @pFirstName = N'Admin',
753 @pLastName = N'Administrator',
754 @responseMessage=@responseMessage
755OUTPUT
756SELECT UserID, LoginName, PasswordHash, Salt, FirstName, LastName from tblUser
757
758
759
760
761CREATE PROCEDURE uspLogin
762 @pLoginName NVARCHAR(254),
763 @pPassword NVARCHAR(50),
764 @responseMessage NVARCHAR(250)='' OUTPUT
765AS
766BEGIN
767 SET NOCOUNT ON
768 DECLARE @userID INT
769
770 IF EXISTS (SELECT TOP 1 UserID FROM tblUser where LoginName=@pLoginName)
771 BEGIN
772 SET @userID = (SELECT UserID FROM tblUser WHERE LoginName = @pLoginName AND PasswordHash = HASHBYTES('MD2', @pPassword+CAST(Salt AS NVARCHAR(36))))
773
774 IF(@UserID IS NULL)
775 SET @responseMessage='Incorrect password'
776 ELSE
777 SET @responseMessage='User successfully logged in'
778 END
779 ELSE
780 SET @responseMessage='Invalid login'
781END
782
783Command(s) completed successfully.
784
785
786DECLARE @responseMessage NVARCHAR(250)
787EXEC uspLogin
788 @pLoginName = N'Admin',
789 @pPassword = N'123',
790 @responseMessage = @responseMessage
791OUTPUT
792SELECT @responseMessage as N'responseMessage'
793
794
795
796DECLARE @responseMessage NVARCHAR(250)
797EXEC uspLogin
798 @pLoginName = N'Admin1',
799 @pPassword = N'123',
800 @responseMessage = @responseMessage
801OUTPUT
802SELECT @responseMessage as N'responseMessage'
803
804
805
806DECLARE @responseMessage NVARCHAR(250)
807EXEC uspLogin
808 @pLoginName = N'Admin',
809 @pPassword = N'12322',
810 @responseMessage = @responseMessage
811OUTPUT
812SELECT @responseMessage as N'responseMessage'
813
814
815
816
817
818Method 4 : Single Cell Encryption
819Step 1 - Create a sample SQL Server table
820create table cust
821(
822 CustId int Primary key not null,
823 Name varchar(50) not null,
824 AccNo varchar(10) not null,
825 TypeOfAcc varchar(10) not null
826);
827
828Command(s) completed successfully.
829
830
831insert into cust values(1001,'Hina','S1001','Saving');
832(1 row(s) affected)
833
834
835insert into cust values(1002,'Siddhi','C2001','Current');
836(1 row(s) affected)
837
838insert into cust values(1003,'Shreyash','C2004','Current');
839(1 row(s) affected)
840
841insert into cust values(1004,'Shameena','C2007','Current');
842(1 row(s) affected)
843
844insert into cust values(1005,'Sanesh','S1004','Saving');
845(1 row(s) affected)
846Step 2 - SQL Server Service Master Key
847
848USE master;
849GO
850SELECT *
851FROM sys.symmetric_keys
852WHERE name = '##MS_ServiceMasterKey##';
853GO
854
855
856
857Step 3 - SQL Server Database Master Key
858use hina;
859go
860create master key encryption by password='password123';
861go
862
863Command(s) completed successfully.
864
865Step 4 - Create a Self Signed SQL Server Certificate:
866
867use hina;
868go
869create certificate certificate1
870with subject='Protect Data';
871go
872
873Command(s) completed successfully.
874
875
876Step 5 - SQL Server Symmetric Key
877use hina;
878go
879create symmetric key symmetricKey1
880with algorithm=AES_128
881encryption by certificate certificate1;
882go
883
884Command(s) completed successfully.
885
886Step 6 - Schema changes
887use hina;
888go
889alter table cust
890add AccNoEncrypt nvarchar(MAX) NULL;
891go
892
893Command(s) completed successfully.
894
895UPDATE cust
896SET AccNoEncrypt = EncryptByKey AccNo
897FROM cust;
898
899Command(s) completed successfully.
900
901
902Step 7 - Remove old column
903alter table cust
904drop column AccNo;
905
906
907insert into cust values (1006,'Tejas','Saving', 'S1007');
908Step 8 - Encrypting one cell
909open symmetric key symmetricKey1
910decryption by certificate certificate1;
911go
912update [db].[dbo].[cust]
913set AccNoEncrypt=ENCRYPTBYKEY(KEY_GUID('symmetricKey1'),'S1007')
914where CustId=1006;
915
916(1 row(s) affected)
917
918SELECT * FROM [db].[dbo].[cust]
919
920
921Method 5 : Row level Encryption
922Step 1 - Create a sample SQL Server table
923create table demo
924(
925 Name nvarchar(MAX),
926 AccNo nvarchar(MAX)
927);
928
929Command(s) completed successfully.
930
931insert into demo values('Hina','S1001');
932
933insert into demo values('Siddhi','C2001');
934
935insert into demo values('Shreyash','C2004');
936
937insert into demo values('Shameena','C2007');
938
939insert into demo values('Sanesh','S1004');
940
941Step 2 - SQL Server Service Master Key
942
943USE master;
944GO
945SELECT *
946FROM sys.symmetric_keys
947WHERE name = '##MS_ServiceMasterKey##';
948GO
949
950
951
952Step 3 - SQL Server Database Master Key
953use hina;
954go
955create master key encryption by password='password123';
956go
957
958Command(s) completed successfully.
959
960Step 4 - Create a Self Signed SQL Server Certificate:
961
962use hina;
963go
964create certificate certificate1
965with subject='Protect Data';
966go
967
968Command(s) completed successfully.
969
970
971Step 5 - SQL Server Symmetric Key
972use hina;
973go
974create symmetric key symmetricKey1
975with algorithm=AES_128
976encryption by certificate certificate1;
977go
978
979Command(s) completed successfully.
980
981Step 6 - Inserting Encrypted Values
982open symmetric key symmetricKey1
983decryption by certificate certificate1;
984
985insert into demo values (ENCRYPTBYKEY(KEY_GUID('symmetricKey1'),'Tejas'),ENCRYPTBYKEY(KEY_GUID('symmetricKey1'),'S1007'));
986
987
988
989(1 row(s) affected)
990
991select * from demo
992
993 
994PRACTICAL NO. 3
995Aim : Create a honeypot and demonstrate the following –
996a) Penetration
997b) Phishing
998
999 Description:- Ping Flood Attack
1000 How to Perform:-
1001 Step 1:-
1002 Detect Target Address through Zenmap using starting adress of IP adress and mask adress
1003 e.g. Here I am targeting IP address 192.168.2.190
1004
1005
1006Step 2:-
1007 Ping to target machine as follow:-
1008
1009
1010Detection:-
1011Step 1:-
1012Search for ICMP
1013
1014
1015
1016
1017Step 2:-
1018Go to Statistic==>Endpoints
1019 Find length of Packet
1020
1021Step 3:-
1022Get location from LAN IP address as follows:-
1023
1024
1025
1026
1027
1028
1029
10302)Brute force attack
1031Software used: Cain and able
1032Step: 1) Open cain and able. Click on Start/Stop sniffer. Click on + sign and add the ip of the network.
1033
1034
1035
1036Step: 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.
1037
1038Step: 3) Open a browser and visit any Not Secured website. Enter the user id and password and submit.
1039
1040
1041Step: 4) Click on the passwords tab at the bottom of the screen. Click on HttP and the passwords will be displayed.
1042
1043
1044
1045
10463 ) ARP Flooding:
1047Software Used: Colasoft
1048Open Colasoft.
1049Check the network adapter for connection.
1050
1051
1052Click on add in the top left corner of the screen.
1053Select the ARP Packet. Let time be default.
1054
1055
1056Click Ok and proceed.
1057Now enter the mac and ip address of the source and destination where necessary.
1058
1059
1060Now select the packet in the Packet list. Right Click on the packet and click on send selected packets.
1061
1062
1063Select the adapter and insert the values. Then Click start.
1064
1065
1066ARP packets will start broadcasting.
1067
1068Now Trace the network with wireshark on the destination machine.
1069
1070The network is flooded with ARP packets originating from the source machine.
1071PRACTICAL NO. 4
1072Aim : Configure and implement SSL/TSL for any webpages to maintain secure session communication.
1073EchoServer.java
1074import javax.net.ssl.*;
1075import java.io.*;
1076public class EchoServer
1077{
1078 public static void main(String[] arstring)
1079 {
1080 try
1081 {
1082 SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
1083 SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
1084 SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
1085 InputStream is = sslSocket.getInputStream();
1086 InputStreamReader isReader = new InputStreamReader(is);
1087 BufferedReader br = new BufferedReader(isReader);
1088 String string = null;
1089 while ((string = br.readLine()) != null)
1090 {
1091 System.out.println(string);
1092 System.out.flush();
1093 }
1094 }
1095 catch (Exception e)
1096 {
1097 e.printStackTrace();
1098 }
1099 }
1100}
1101
1102EchoClient.java
1103import javax.net.ssl.*;
1104import java.io.*;
1105public class EchoClient
1106{
1107 public static void main(String[] arstring)
1108 {
1109 try
1110 {
1111 SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
1112 SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
1113 InputStream is = System.in;
1114 InputStreamReader isReader = new InputStreamReader(is);
1115 BufferedReader br = new BufferedReader(isReader);
1116 OutputStream os = sslSocket.getOutputStream();
1117 OutputStreamWriter osWriter = new OutputStreamWriter(os);
1118 BufferedWriter bw = new BufferedWriter(osWriter);
1119 String string = null;
1120 while ((string = br.readLine()) != null)
1121 {
1122 bw.write(string + '\n');
1123 bw.flush();
1124 }
1125 }
1126 catch (Exception e)
1127 {
1128 e.printStackTrace();
1129 }
1130 }
1131}
1132
1133Output :
1134
1135
1136
1137
1138 
1139PRACTICAL NO. 5
1140Aim : Write a program to send an encrypted Email which allows the user to choose the type of encryption. Implement any 3 techniques.
1141
1142Code: -
1143package encryptmail;
1144import com.sun.mail.util.BASE64EncoderStream;
1145import java.security.KeyPair;
1146import java.security.KeyPairGenerator;
1147import java.security.PrivateKey;
1148import java.security.PublicKey;
1149import java.util.Properties;
1150import java.util.Scanner;
1151import javax.crypto.*;
1152import javax.mail.*;
1153import javax.mail.internet.*;
1154import sun.misc.BASE64Encoder;
1155
1156public class EncryptMail
1157{
1158 public static void main(String[] args)
1159 {
1160 Scanner sc=new Scanner(System.in);
1161System.out.println("Choose the Algorithm for email encryption\n1.AES\n2.DES\n3.RSA");
1162intalgoN=sc.nextInt();
1163 String algo="null";
1164 if(algoN==1)
1165 {
1166algo="AES";
1167 }
1168 if(algoN==2)
1169 {
1170algo="DES";
1171 }
1172 if(algoN==3)
1173 {
1174algo="RSA";
1175 }
1176 String to="adityasahastrabudhe97@gmail.com";
1177 Properties props = new Properties();
1178props.put("mail.smtp.starttls.enable","true");
1179props.put("mail.smtp.host", "smtp.gmail.com");
1180props.put("mail.smtp.ssl.trust","smtp.gmail.com");
1181props.put("mail.smtp.socketFactory.port", "465");
1182 props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
1183props.put("mail.smtp.auth", "true");
1184props.put("mail.smtp.port", "465");
1185
1186 Session session = Session.getDefaultInstance(props,newjavax.mail.Authenticator()
1187 {
1188 protected PasswordAuthenticationgetPasswordAuthentication()
1189 {
1190 return new PasswordAuthentication("adityasahastrabudhe97@gmail.com","123");
1191 }
1192 });
1193 try
1194 {
1195
1196 String cipherText="",decryptedText;
1197 String msg="hello";
1198
1199 if(algo.equals("AES"))
1200 {
1201KeyGeneratorkeyGen=KeyGenerator.getInstance(algo);
1202keyGen.init(128);
1203SecretKeysecretKey=keyGen.generateKey();
1204 Cipher aesCipher=Cipher.getInstance(algo);
1205aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
1206byte[] byteDataToEncrypt=msg.getBytes();
1207byte[] byteCipherText=aesCipher.doFinal(byteDataToEncrypt);
1208cipherText=new BASE64Encoder().encode(byteCipherText);
1209 }
1210 if(algo.equals("RSA"))
1211 {
1212 final intkeySize = 2048;
1213KeyPairGeneratorkeyPairGenerator = KeyPairGenerator.getInstance("RSA");
1214keyPairGenerator.initialize(keySize);
1215KeyPairkeyPair = keyPairGenerator.genKeyPair();
1216PublicKeypubKey = keyPair.getPublic();
1217
1218PrivateKeyprivateKey = keyPair.getPrivate();
1219 Cipher cipher = Cipher.getInstance("RSA");
1220cipher.init(Cipher.ENCRYPT_MODE, privateKey);
1221 byte [] encrypted = cipher.doFinal(msg.getBytes());
1222cipherText=new String(encrypted);
1223 }
1224 if(algo.equals("DES"))
1225 {
1226SecretKey key;
1227 Cipher ecipher;
1228 key = KeyGenerator.getInstance("DES").generateKey();
1229ecipher = Cipher.getInstance("DES");
1230ecipher.init(Cipher.ENCRYPT_MODE, key);
1231byte[] utf8 = msg.getBytes("UTF8");
1232byte[] enc = ecipher.doFinal(utf8);
1233enc = BASE64EncoderStream.encode(enc);
1234cipherText= new String(enc);
1235 }
1236
1237MimeMessage message = new MimeMessage(session);
1238message.setFrom(new InternetAddress("adityasahastrabudhe97@gmail.com"));
1239message.addRecipient(Message.RecipientType.TO,newInternetAddress(to));
1240message.setSubject("Hello");
1241message.setText(cipherText);
1242Transport.send(message);
1243System.out.println("message sent successfully");
1244 }
1245 catch (Exception e)
1246 {
1247e.printStackTrace();
1248 }
1249 }
1250}
1251
1252
1253
1254
1255
1256
1257Output: -
1258Choose the Algorithm for email encryption
12591.AES
12602.DES
12613.RSA
12621
1263message sent successfully.
1264 
1265PRACTICAL NO. 6
1266Aim : Implement ESX file system security in cloud.
1267
1268Prerequisites
1269To run this quickstart, you'll need:
1270• Python 2.6 or greater.
1271• The pip package management tool.
1272• A Google account with Google Drive enabled.
1273Step 1: Turn on the Drive API
1274a. 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.
1275b. On the Add credentials to your project page, click the Cancel button.
1276c. 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.
1277d. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
1278e. Select the application type Other, enter the name "Drive API Quickstart", and click the Create button.
1279f. Click OK to dismiss the resulting dialog.
1280g. Click the file_download (Download JSON) button to the right of the client ID.
1281h. Move this file to your working directory and rename it client_secret.json.
1282
1283Step 2: Install the Google Client Library
1284Run the following command to install the library using pip:
1285pip install --upgrade google-api-python-client
1286See the library's installation page for the alternative installation options.
1287
1288Step 3: Copy paste the bellow code in another file and execute the file using :
1289python filename
1290
1291Code:
1292from __future__ import print_function
1293import httplib2
1294import os
1295import random
1296
1297from apiclient import discovery
1298from apiclient.http import MediaFileUpload
1299from oauth2client import client
1300from oauth2client import tools
1301from oauth2client.file import Storage
1302
1303from Crypto.Cipher import AES
1304from Crypto.Hash import SHA256
1305
1306try:
1307 import argparse
1308 flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
1309except ImportError:
1310 flags = None
1311
1312SCOPES = 'https://www.googleapis.com/auth/drive'
1313CLIENT_SECRET_FILE = 'client_secret.json'
1314APPLICATION_NAME = 'Drive API Python Quickstart'
1315
1316def get_credentials():
1317 # checks if credentials are present. if not creates new dir and stores credentials in it.
1318 # creates dir if dir is not present.
1319credential_dir = os.path.join(os.getcwd(), '.credentials')
1320 if not os.path.exists(credential_dir):
1321os.makedirs(credential_dir)
1322credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json')
1323
1324 # gets credentials
1325 store = Storage(credential_path)
1326 credentials = store.get()
1327
1328 # if credentials not found, creates credentials by receiving authorization from user using authentication flow and stores in cwd
1329 if not credentials or credentials.invalid:
1330 flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
1331flow.user_agent = APPLICATION_NAME
1332 if flags:
1333 credentials = tools.run_flow(flow, store, flags)
1334 else: # Needed only for compatibility with Python 2.6
1335 credentials = tools.run(flow, store)
1336print('Storing credentials to ' + credential_path)
1337 return credentials
1338
1339def get_service():
1340 credentials = get_credentials()
1341 http = credentials.authorize(httplib2.Http())
1342drive_service = discovery.build('drive', 'v3', http=http)
1343 return drive_service
1344
1345def get_key(password):
1346 # creates SHA256 hash of the password
1347 password = password.encode('ascii')
1348 hasher = SHA256.new(password)
1349 return hasher.digest()
1350
1351def encrypt_file(file_name, key):
1352 # encrypts the file with the provided key using AES-128
1353chuncksize = 64 * 1024
1354outputfilename = file_name + ".enc"
1355filesize = str(os.path.getsize(file_name)).zfill(16)
1356 IV = ''
1357
1358 for i in range(16):
1359 IV += chr(random.randint(97, 123))
1360 IV = IV.encode('ascii')
1361encryptor = AES.new(key, AES.MODE_CBC, IV)
1362
1363 with open(file_name, 'rb') as infile:
1364 with open(outputfilename, 'wb') as outfile:
1365outfile.write(filesize.encode('ascii'))
1366outfile.write(IV)
1367
1368 while True:
1369chunck = infile.read(chuncksize)
1370
1371 if(len(chunck) == 0):
1372 break
1373 if(len(chunck) % 16 != 0):
1374chunck += (' ' * (16 - len(chunck) % 16)).encode('ascii')
1375outfile.write(encryptor.encrypt(chunck))
1376 return outputfilename
1377
1378
1379def upload_file(drive_service, filename, filepath):
1380file_metadata = {'name': filename}
1381 media = MediaFileUpload(filepath)
1382 file = drive_service.files().create(body=file_metadata,
1383media_body=media, fields='id').execute()
1384print('File ID: %s' % file.get('id'))
1385
1386
1387def main():
1388drive_service = get_service()
1389
1390file_name = input("Name of the file you want to encrypt and upload: ")
1391 password = input("Enter the password to encrypt the file: ")
1392print("Encrypting file...")
1393encrypted_file = encrypt_file(file_name, get_key(password))
1394print("Uploading encrypted file...")
1395upload_file(drive_service, encrypted_file, encrypted_file)
1396print("File uploaded succesfully.")
1397
1398
1399if __name__ == '__main__':
1400main()
1401
1402
1403
1404 
1405PRACTICAL NO. 7
1406PRACTICAL NO.7: Write a program to generate DSA SSH key.
1407Export.java
1408import java.io.*;
1409importjava.security.*;
1410importjava.security.spec.DSAPrivateKeySpec;
1411public class Export
1412{
1413public static void main(String args[])
1414 {
1415try
1416 {
1417KeyPairGeneratorkpg = KeyPairGenerator.getInstance("DSA");
1418SecureRandomrnd = SecureRandom.getInstance("SHA1PRNG","SUN");
1419kpg.initialize(1024,rnd);
1420KeyPairkp = kpg.generateKeyPair();
1421
1422 Class spec = Class.forName("java.security.spec.DSAPrivateKeySpec");
1423KeyFactorykf = KeyFactory.getInstance("DSA");
1424DSAPrivateKeySpecks = (DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(), spec);
1425
1426FileOutputStreamfos = new FileOutputStream("ExportedKey.txt");
1427ObjectOutputStreamoos = new ObjectOutputStream(fos);
1428
1429oos.writeObject(ks.getX());
1430oos.writeObject(ks.getP());
1431oos.writeObject(ks.getQ());
1432oos.writeObject(ks.getG());
1433
1434System.out.println("Private Key Exported");
1435 }
1436catch(Exception e)
1437 {
1438e.printStackTrace();
1439 }
1440 }
1441}
1442
1443OUTPUT:
1444
1445
1446Import.java
1447import java.io.*;
1448importjava.math.BigInteger;
1449importjava.security.*;
1450importjava.security.spec.DSAPrivateKeySpec;
1451public class Import
1452{
1453public static void main(String args[])
1454 {
1455try
1456 {
1457FileInputStreamfis = new FileInputStream("exportedKey.txt");
1458ObjectInputStreamois = new ObjectInputStream(fis);
1459
1460DSAPrivateKeySpecks = new DSAPrivateKeySpec((BigInteger)ois.readObject(),(BigInteger)ois.readObject(),(BigInteger)ois.readObject(),(BigInteger)ois.readObject());
1461
1462KeyFactorykf = KeyFactory.getInstance("DSA");
1463PrivateKeypk = kf.generatePrivate(ks);
1464
1465System.out.println("Got private key.");
1466 }
1467catch(FileNotFoundException e)
1468 {
1469System.out.println("Key not found.");
1470 }
1471catch(Exception e)
1472 {
1473System.out.println("Key is corrupted.");
1474 }
1475 }
1476}
1477
1478OUTPUT:
1479
1480
1481
1482
1483
1484
1485
1486
1487PRACTICAL NO. 8
1488Demonstrate and implement Bluetooth security.
1489Requirements
14901. pc with bluetooth
14912. python lightblue package
14923. python version 2.7
14934. target device needs to be paired with the host device
1494
1495
1496Command to install lightblue package
1497sudo apt-get install python-lightblue --(internet required)
1498
1499Code :
1500import bluetooth
1501import lightblue
1502import os
1503import random
1504
1505from Crypto.Cipher import AES
1506from Crypto.Hash import SHA256
1507
1508def get_nearby_devices():
1509 #searches for nearby devices
1510 print "searching for nearby devices..."
1511 nearby_devices = bluetooth.discover_devices()
1512 return nearby_devices
1513
1514def is_target_on(nearby_devices,target_name):
1515 #checks if target is on
1516 for bdaddr in nearby_devices:
1517 print bluetooth.lookup_name(bdaddr)
1518 if target_name == bluetooth.lookup_name(bdaddr):
1519 print "found the target device!"
1520 target_address = bdaddr
1521 print"Target Address: " + target_address
1522 return target_address
1523 return None
1524
1525
1526def get_services(target_address):
1527 #gets the list of all services the target provides over bluetooth
1528 print "searching for the object push service..."
1529 services = lightblue.findservices(target_address)
1530 print services
1531
1532def get_key(password):
1533 # creates SHA256 hash of the password
1534 hasher = SHA256.new(password)
1535 return hasher.digest()
1536
1537def encrypt_file(file_name, key):
1538 # encrypts the file with the provided key using AES-128
1539 chuncksize = 64*1024
1540 outputfile = file_name +".enc"
1541 filesize = str(os.path.getsize(file_name)).zfill(16)
1542 IV = ''
1543
1544 for i in range(16):
1545 IV += chr(random.randint(0,0xFF))
1546 encryptor = AES.new(key, AES.MODE_CBC, IV)
1547
1548 with open(file_name, 'rb') as infile:
1549 with open(outputfile, 'wb') as outfile:
1550 outfile.write(filesize)
1551 outfile.write(IV)
1552
1553 while True:
1554 chunck = infile.read(chuncksize)
1555
1556 if(len(chunck) == 0):
1557 break
1558 if(len(chunck) % 16 != 0):
1559 chunck += ' ' * (16 - len(chunck)%16)
1560 outfile.write(encryptor.encrypt(chunck))
1561 outfile.close()
1562 return outputfile
1563
1564
1565
1566if __name__ == '__main__':
1567 # we should know
1568 file_name = raw_input("Enter the name of the file you want to send: ")
1569 password = raw_input("Enter password to encrypt file: ")
1570 file_to_send = encrypt_file(file_name, get_key(password))
1571
1572 # we don't know yet
1573 obex_port = None
1574 target_address = None
1575
1576 nearby_devices = get_nearby_devices()
1577
1578 devices = []
1579 for mac in nearby_devices:
1580 print bluetooth.lookup_name(mac)
1581 devices.append(mac)
1582
1583 target_index = int(raw_input("Enter the index of device: "))
1584 target_address = devices[target_index]
1585 # target_address = is_target_on(nearby_devices,target_name)
1586 get_services(target_address)
1587 obex_port = int(raw_input("Enter the obex port: "))
1588 print "sending a file..."
1589 lightblue.obex.sendfile(target_address, obex_port, file_to_send)
1590 print "File sent."
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612PRACTICAL NO. 9
1613Develop application to implement Zigbee security.
1614
1615• Open Xctu application
1616• Click on the discover devices.
1617
1618• Next the discoverable window will be start.
1619• Select the device connected to the the xctu.
1620• Then Click next.
1621
1622
1623• Do not change the parameters in the next window.
1624• Click on finish button.
1625
1626
1627Let the application load the module
1628After it detects the module press add selected device.
1629
1630
1631
1632
1633• After clickingon the add slected this the main window will start with the decice name and the amc address.
1634• Doublic click on it to open the properties of it in the right pane of the application.
1635
1636
1637• Change the pan id according to your need.
1638• Write the changes by clicking the write button.
1639
1640
1641• After write the changes click on the console button on the application bar to open the console window.
1642• Press the open button to create a connection with the other zigbee.
1643
1644
1645
1646• Type any msg in the console and it display it on the consooe of other zigbee.
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657Sending Code
1658void setup() {
1659 // put your setup code here, to run once:
1660Serial.begin(9600);
1661
1662}
1663
1664void loop() {
1665 // put your main code here, to run repeatedly:
1666 Serial.print("Hello World");
1667 delay(5000);
1668}
1669Receive Code
1670void setup() {
1671 // put your setup code here, to run once:
1672Serial.begin(9600);
1673}
1674
1675void loop() {
1676 // put your main code here, to run repeatedly:
1677 if(Serial.available()>0)
1678 {
1679 Serial.write(Serial.read());
1680 }
1681}