Guest User

Untitled

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