· 6 years ago · Jun 27, 2019, 01:30 AM
1* Practical 1
2** Aim
3#+BEGIN_VERSE
4Write a program to store username and password in an encrypted form in a
5database to implement integrity lock.
6#+END_VERSE
7** Theory
8Data integrity is the maintenance of, and the assurance of the accuracy and
9consistency of, data over its entire life-cycle, and is a critical aspect to the
10design, implementation and usage of any system which stores, processes, or
11retrieves data. The term is broad in scope and may have widely different
12meanings depending on the specific context – even under the same general
13umbrella of computing. It is at times used as a proxy term for data quality,
14while data validation is a pre-requisite for data integrity. Data integrity is
15the opposite of data corruption. The overall intent of any data integrity
16technique is the same: ensure data is recorded exactly as intended (such as a
17database correctly rejecting mutually exclusive possibilities,) and upon later
18retrieval, ensure the data is the same as it was when it was originally
19recorded.
20** Implementation
21#+BEGIN_SRC java
22package src;
23import java.sql.Connection;
24import java.sql.DriverManager;
25import java.sql.PreparedStatement;
26import java.sql.SQLException;
27import java.util.logging.Level;
28import java.util.logging.Logger;
29import javax.crypto.Cipher;
30import javax.crypto.KeyGenerator;
31import javax.crypto.SecretKey;
32public class frame1 extends javax.swing.JFrame
33{
34 Cipher cipher;
35 SecretKey key;
36 Connection con;
37 public frame1()
38 {
39 initComponents();
40 }
41 private void b1ActionPerformed(java.awt.event.ActionEvent evt)
42 {
43 try
44 {
45 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
46 con=DriverManager.getConnection("jdbc:odbc:msc4");
47 con.setAutoCommit(false);
48 cipher=Cipher.getInstance("DESede");
49 key = KeyGenerator.getInstance("DESede").generateKey();
50 String username=txt1.getText();
51 String password=pwd.getText();
52 byte[] uname=encrypt(username);
53 byte[] pass=encrypt(password);
54 String query="insert into login values(?,?)";
55 PreparedStatement pst=con.prepareStatement(query);
56 pst.setBytes(1,uname);
57 pst.setBytes(2,pass);
58 System.out.println("Encrypted username is:"+uname);
59 System.out.println("Encrypted password is:"+pass);
60 pst.executeUpdate();
61 con.commit();
62 }
63 catch( Exception e)
64 {
65 try
66 {
67 con.rollback();
68 e.printStackTrace();
69 }
70 catch (SQLException ex)
71 {
72 Logger.getLogger(frame1.class.getName()).log(Level.SEVERE, null,
73 ex);
74 }
75 }
76 }
77 private byte[] encrypt(String data)
78 {
79 byte[] encryptedString=null;
80 try
81 {
82 cipher.init(Cipher.ENCRYPT_MODE,key);
83 encryptedString=cipher.doFinal(data.getBytes());
84 }
85 catch(Exception e)
86 {
87 e.printStackTrace();
88 }
89 return encryptedString;
90 }
91 public static void main(String args[])
92 {
93 java.awt.EventQueue.invokeLater(new Runnable()
94 {
95 public void run()
96 {
97 new frame1().setVisible(true);
98 }
99 });
100 }
101}
102#+END_SRC
103** Output
104[[./op/p1-1.png]]
105
106[[./op/p1-2.png]]
107
108[[./op/p1-3.png]]
109* Practical 2
110** Aim
111#+BEGIN_VERSE
112Write SQL query to retrieve sensitive information from less sensitive
113queries.
114#+END_VERSE
115** Theory
116Sensitive information is data that must be protected from unauthorized access to
117safeguard the privacy or security of an individual or organization.
118
119There are three main types of sensitive information: Personal information:
120Sensitive personally identifiable information (PII) is data that can be traced
121back to an individual and that, if disclosed, could result in harm to that
122person. Such information includes biometric data, medical information,
123personally identifiable financial information (PIFI) and unique identifiers such
124as passport or Social Security numbers.
125
126Business information: Sensitive business information includes anything that
127poses a risk to the company in question if discovered by a competitor or the
128general public. Such information includes trade secrets, acquisition plans,
129financial data and supplier and customer information, among other possibilities.
130
131Classified information: Classified information pertains to a government body and
132is restricted according to level of sensitivity (for example, restricted,
133confidential, secret and top secret). Information is generally classified to
134protect security. Once the risk of harm has passed or decreased, classified
135information may be declassified and, possibly, made public.
136
137** Implementation and Output
138#+BEGIN_SRC sql
139SQL> create table student(name varchar2(20),sex varchar2(2),race varchar2(20), aid
140number(10), fines number(10), drugs number(10), dorm varchar2(20));
141Table created.
142SQL> insert into student values('Adams','M','c',5000,45,1,'Holmes');
1431 row created.
144SQL> insert into student values('Bailey','M','B',0,0,0,'Grey');
1451 row created.
146SQL> insert into student values('Chin','F','A',3000,20,0,'West');
1471 row created.
148SQL>insert into student values('Dewitt','M','B',1000,35,3,'Grey');
1491 row created.
150SQL> insert into student values('Earhart','F','C',2000,95,1,'Holmes');
1511 row created.
152SQL> insert into student values('Fein','F','C',1000,15,0,'West');
1531 row created.
154SQL>insert into student values('Groff','M','C',4000,0,3,'West');
1551 row created.
156SQL> insert into student values('Hill','F','B',5000,10,2,'Holmes');
1571 row created.
158SQL> insert into student values('Koch','F','C',0,0,1,'West');
1591 row created.
160SQL> insert into student values('Liu','F','A',0,10,2,'Grey');
1611 row created.
162SQL> insert into student values('Majors','M','C',2000,0,2,'Grey');
1631 row created.
164#+END_SRC
165
166*** Direct Attack
167**** Display names of males having drug count as 1.
168#+BEGIN_SRC sql
169SQL> select name from student where drug=1 and sex='M';
170NAME
171----------
172ADAMS
173#+END_SRC
174**** Display names of males where drug count is 1 or dorm is Aryes.
175#+BEGIN_SRC sql
176SQL> select name from student where( drug=1 and sex=’M’) or dorm=’Aryes’;
177NAME
178----------
179ADAMS
180#+END_SRC
181*** Indirect Attack
182**** Find student aid total by sex and dorm.
183#+BEGIN_SRC sql
184SQL> select aid from student where sex='M' and dorm='Holmes';
185AID
186----------
1875000
188SQL> select sum(aid) from student where sex='F' and dorm='Holmes';
189SUM(AID)
190----------
1917000
192SQL> select sum(aid) from student where dorm='Holmes';
193SUM(AID)
194----------
19512000
196SQL> select sum(aid)from student where sex='M' and dorm='Grey';
197SUM(AID)
198----------
1993000
200SQL> select sum(aid)from student where sex='F' and dorm='Grey';
201SUM(AID)
202----------
2030
204SQL> select sum(aid) from student where dorm='Grey';
205SUM(AID)
206----------
2073000
208SQL> select sum(aid)from student where sex='M' and dorm='West';
209SUM(AID)
210----------
2114000
212SQL> select sum(aid)from student where sex='F' and dorm='West';
213SUM(AID)
214----------
2154000
216SQL> select sum(aid) from student where dorm='West';
217SUM(AID)
218----------
2198000
220SQL>select sum(aid) from student where sex='M' and (dorm='Holmes' or dorm='Grey'
221or dorm='West')
222SUM(AID)
223----------
22412000
225SQL> select sum(aid) from student where sex='F' and (dorm='Holmes' or dorm='Grey'
226or dorm='West')
227SUM(AID)
228----------
22911000
230SQL> select sum(aid) from student where (sex='M' or sex='F') and (dorm='Holmes' or
231dorm='Grey' or d
232orm='West');
233SUM(AID)
234----------
23523000
236#+END_SRC
237**** Count record of student by sex and dorm.
238#+BEGIN_SRC sql
239SQL> select count(sex) from student where sex='M' and dorm='Holmes';
240SQL> /
241COUNT(SEX)
242----------
2431
244SQL> select count(sex) from student where sex='F' and dorm='Holmes';
245COUNT(SEX)
246----------
2472
248SQL> select count(sex) from student where dorm='Holmes';
249COUNT(SEX)
250----------
2513
252SQL> select count(sex) from student where sex='M' and dorm='Grey';
253COUNT(SEX)
254----------
2553
256SQL> select count(sex) from student where sex='F' and dorm='Grey';
257COUNT(SEX)
258----------
2591
260SQL> select count(sex) from student where dorm='Grey';
261COUNT(SEX)
262----------
2634
264SQL> select count(sex) from student where sex='M' and dorm='West';
265COUNT(SEX)
266----------
2671
268SQL> select count(sex) from student where sex='F' and dorm='West';
269COUNT(SEX)
270----------
2713
272SQL> select count(sex) from student where dorm='West';
273COUNT(SEX)
274----------
2754
276SQL>select count(sex) from student where sex='M' and (dorm='West' or dorm='Grey'
277or dorm='Holmes')
278COUNT(SEX)
279----------
2805
281SQL> select count(sex) from student where sex='F' and (dorm='West' or dorm='Grey' or
282dorm='Holmes');
283COUNT(SEX)
284----------
285SQL> select count(sex) from student where (sex='M' or sex='F') and (dorm='West' or
286dorm='Grey' or do
287rm='Holmes');
288COUNT(SEX)
289----------
29011
291#+END_SRC
292**** Find names of student
293#+BEGIN_SRC sql
294SQL> select name from student where sex='M' and dorm='Holmes';
295NAME
296--------------------
297Adams
298SQL>select name from student where sex='M' and dorm='West'
299NAME
300--------------------
301Groff
302SQL>select name from student where sex='F' and dorm='Grey'
303NAME
304--------------------
305Liu
306#+END_SRC
307*** Tracker Attack
308**** Display AID from Students where Sex=’M’ and Drugs=2 group by Aid.
309#+BEGIN_SRC sql
310SQL> select (select sum(aid) from student where sex='M')-(select sum(aid) from student
311where sex='M' and ((sex='M' and drugs<>2) or (sex<>'M' and sex<>'F'))) "AID" from
312dual;
313AID
314----------
3152000
316#+END_SRC
317**** Display how many females with Race as Caucasians live in dorm as Holmes.
318#+BEGIN_SRC sql
319SQL> SELECT ((select count(sex) from student where sex='F') -(select count(sex) from
320student where sex='F' and dorm='Holmes')) FROM DUAL;
321RESULT
322----------
3231
324#+END_SRC
325* Practical 3
326** Aim
327#+BEGIN_VERSE
328Write SQL query to create a view to implement concept of views and
329commutative filter in distributed databases.
330#+END_VERSE
331** Implementation and Output
332*** Login:system, Password:tiger, Hoststring: orcl
333#+BEGIN_SRC sql
334SQL> create user u1 identified by secret1;
335User created.
336SQL> grant create session,create table,create sequence,create view to u1;
337Grant succeeded.
338SQL> grant connect,resource to u1;
339Grant succeeded.
340SQL> create user u2 identified by secret2;
341User created.
342SQL> grant create session,create table,create sequence,create view to u2;
343Grant succeeded.
344SQL> grant connect,resource to u2;
345Grant succeeded.
346SQL> create user u3 identified by secret3;
347User created.
348SQL> grant create session,create table,create sequence,create view to u3;
349Grant succeeded.
350SQL> grant connect,resource to u3;
351Grant succeeded.
352#+END_SRC
353*** Login:scott, Password: tiger, hoststring: orcl
354#+BEGIN_SRC sql
355SQL> create table emp(eno number(5),ename varchar2(20),address varchar2(50),email
356varchar2(40),sal number(8));
357Table created.
358SQL> insert into emp values(101,'Simran','Ghatkopar','sk@gmail.com',50000);
3591 row created.
360SQL> insert into emp values(102,'Harshada','Vikroli','hs@gmail.com',48000);
3611 row created.
362SQL> insert into emp values(103,'Jyoti','Thane','jv@yahoo.com',30000);
3631 row created.
364SQL> insert into emp values(104,'Ritu','Sion','rp@gmail.com',55000);
3651 row created.
366SQL> insert into emp values(105,'Asees','Andheri','ag@hotmail.com',50000);
3671 row created.
368SQL> select * from emp;
369ENO ENAME
370---------- --------------------
371ADDRESS
372--------------------------------------------------
373EMAIL SAL
374---------------------------------------- ----------
375101 Simran
376Ghatkopar
377sk@gmail.com 50000
378
379102 Harshada
380Vikroli
381hs@gmail.com 48000
382
383ENO ENAME
384---------- --------------------
385ADDRESS
386--------------------------------------------------
387EMAIL SAL
388---------------------------------------- ----------
389103 Jyoti
390Thane
391jv@yahoo.com
392Sion 30000
393104 Ritu
394ENO ENAME
395---------- --------------------
396ADDRESS
397--------------------------------------------------
398EMAIL SAL
399---------------------------------------- ----------
400rp@gmail.com 55000
401105 Asees
402Andheri
403ag@hotmail.com 50000
404#+END_SRC
405*** Login: u1, password: secret1, hoststring: orcl
406#+BEGIN_SRC sql
407SQL> create database link user1 connect to scott identified by tiger using 'orcl';
408Database link created.
409SQL> create table emp1 as select eno,ename,address from emp@user1;
410Table created.
411SQL> select * from emp1;
412ENO ENAME
413---------- --------------------
414ADDRESS
415--------------------------------------------------
416101 Simran
417Ghatkopar
418102 Harshada
419Vikroli
420103 Jyoti
421Thane
422ENO ENAME
423---------- --------------------
424ADDRESS
425--------------------------------------------------
426104 Ritu
427Sion
428105 Asees
429Andheri
430#+END_SRC
431*** Login: u2, password: secret2, hoststring: orcl
432#+BEGIN_SRC sql
433SQL> create database link user2 connect to scott identified by tiger using 'orcl';
434Database link created.
435SQL> create table emp2 as select eno,email,sal from emp@user2;
436Table created.
437SQL> select * from emp2;
438ENO EMAIL SAL
439---------- ---------------------------------------- ----------
440101 sk@gmail.com 50000
441102 hs@gmail.com 48000
442103 jv@yahoo.com 30000
443104 rp@gmail.com 55000
444105 ag@hotmail.com 50000
445#+END_SRC
446*** Login: u3, password: secret3, hoststring: orcl
447#+BEGIN_SRC sql
448SQL> create database link user3 connect to u1 identified by secret1 using 'orcl';
449Database link created.
450SQL> create database link user_03 connect to u2 identified by secret2 using 'orcl';
451Database link created.
452SQL> create view v as select e1.eno,e1.ename,e1.address,e2.email from emp1@user3
453e1, emp2@user_03 e2 where e1.eno=e2.eno;
454View created.
455SQL> select * from v;
456ENO ENAME
457---------- --------------------
458ADDRESS
459--------------------------------------------------
460EMAIL
461----------------------------------------
462101 Simran
463Ghatkopar
464sk@gmail.com
465102 Harshada
466Vikroli
467hs@gmail.com
468ENO ENAME
469---------- --------------------
470ADDRESS
471--------------------------------------------------
472EMAIL
473----------------------------------------
474103 Jyoti
475Thane
476jv@yahoo.com
477Sion
478104 Ritu
479ENO ENAME
480---------- --------------------
481ADDRESS
482--------------------------------------------------
483EMAIL
484----------------------------------------
485rp@gmail.com
486105 Asees
487Andheri
488ag@hotmail.com
489#+END_SRC
490* Practical 4
491** Aim
492#+BEGIN_VERSE
493Write a program to implement SSL.
494#+END_VERSE
495** Theory
496SSL (Secure Sockets Layer) is a standard security protocol for establishing
497encrypted links between a web server and a browser in an online communication.
498
499The usage of SSL technology ensures that all data transmitted between the web
500server and browser remains encrypted.An SSL certificate is necessary to create
501SSL connection. You would need to give all details about the identity of your
502website and your company as and when you choose to activate SSL on your web
503server. Following this, two cryptographic keys are created - a Private Key and a
504Public Key. An SSL Certificate comprises of your domain name, the name of your
505company and other things like your address, your city, your state and your
506country. It would also show the expiration date of the SSL plus details of the
507issuing CA (Certification Authority). Whenever a browser initiates a connection
508with a SSL secured website , it will first retrieve the site's SSL Certificate
509to check if it's still valid. It's also verified that the CA is one that the
510browser trusts, and also that the certificate is being used by the website for
511which it has been issued. If any of these checks fail, a warning will be
512displayed to the user, indicating that the website is not secured by a valid SSL
513certificate.
514
515** Implementation
516Steps involved:
517
5181. Write following command on command prompt:
519 keytool -genkey -keystore mySrvKeystore -keyalg RSA
5202. (it will ask for password give password as secret & provide other info
521 when it asks password for mykey press enter)
5223. Create a Java Application(Server program in Netbeans)
5234. Copy mySrvKeystore file & paste into server folder.
5245. Right click on project->properties & make following changes under Run
525 tab:
526 1. Working Directory should be set to current directory
527 2. Write following in VM Options:
528 -D javax.net.ssl.keyStore=mySrvKeystore
529 -D javax.net.ssl.keyStorePassword=secret
5306. Create a Java Application(Client program in Netbeans)
5317. Copy mySrvKeystore file & paste into server folder.
5328. Right click on project->properties & make following changes under Run
533 tab:
534 1. Working Directory should be set to current directory
535 2. Write following in VM Options:
536 -Djavax.net.ssl.trustStore=mySrvKeystore
537 -Djavax.net.ssl.trustStorePassword=secret
538*** SSLServer.java
539#+BEGIN_SRC java
540package sslserver;
541import javax.net.ssl.SSLServerSocket;
542import javax.net.ssl.SSLServerSocketFactory;
543import javax.net.ssl.SSLSocket;
544import java.io.BufferedReader;
545import java.io.InputStream;
546import java.io.InputStreamReader;
547public class SSLServer
548{
549 public static void main(String[] args)
550 {
551 try
552 {
553 SSLServerSocketFactory fac =(SSLServerSocketFactory)
554 SSLServerSocketFactory.getDefault();
555 SSLServerSocket ser_soc = (SSLServerSocket)
556 fac.createServerSocket(9999);
557 SSLSocket ssl_soc = (SSLSocket) ser_soc.accept();
558 BufferedReader br = new BufferedReader(new
559 InputStreamReader(ssl_soc.getInputStream()));
560 String s = null;
561 while ((s = br.readLine()) != null)
562 {
563 System.out.println(s);
564 System.out.flush();
565 }
566 }
567 catch (Exception e)
568 {
569 e.printStackTrace();
570 }
571 }
572}
573#+END_SRC
574*** SSLClient.java
575#+BEGIN_SRC java
576package sslclient;
577import java.io.BufferedReader;
578import java.io.BufferedWriter;
579import java.io.InputStream;
580import java.io.InputStreamReader;
581import java.io.OutputStream;
582import java.io.OutputStreamWriter;
583import javax.net.ssl.SSLSocket;
584import javax.net.ssl.SSLSocketFactory;
585public class SSLClient
586{
587 public static void main(String[] args)
588 {
589 try
590 {
591 SSLSocketFactory fac =
592 (SSLSocketFactory)SSLSocketFactory.getDefault();
593 SSLSocket ssl_soc = (SSLSocket) fac.createSocket("localhost", 9999);
594 BufferedReader br = new BufferedReader(new
595 InputStreamReader(System.in));
596 BufferedWriter bw= new BufferedWriter( new
597 OutputStreamWriter(ssl_soc.getOutputStream()));
598 String s = null;
599 while ((s = br.readLine()) != null)
600 {
601 bw.write(s + '\n');
602 bw.flush();
603 }
604 }
605 catch (Exception e)
606 {
607 e.printStackTrace();
608 }
609 }
610}
611#+END_SRC
612** Output
613#+BEGIN_VERSE
614Demo of SSL using normal java program in Netbeans
615HIII
616#+END_VERSE
617* Practical 5
618** Aim
619#+BEGIN_VERSE
620Write a program to send an encrypted email.
621#+END_VERSE
622** Theory
623Email encryption involves encrypting, or disguising, the content of email
624messages in order to protect potentially sensitive information from being read
625by anyone other than intended recipients. Email encryption often includes
626authentication. Three primary things you should encrypt:
627 1. The connection from your email provider
628 2. Your actual email messages
629 3. Your stored, cached, or archived email messages
630** Implementation
631#+BEGIN_SRC java
632import java.security.InvalidKeyException;
633import java.security.NoSuchAlgorithmException;
634import java.util.Properties;
635import javax.crypto.BadPaddingException;
636import javax.crypto.Cipher;
637import javax.crypto.IllegalBlockSizeException;
638import javax.crypto.KeyGenerator;
639import javax.crypto.NoSuchPaddingException;
640import javax.crypto.SecretKey;
641import javax.mail.Message;
642import javax.mail.MessagingException;
643import javax.mail.PasswordAuthentication;
644import javax.mail.Session;
645import javax.mail.Transport;
646import javax.mail.internet.InternetAddress;
647import javax.mail.internet.MimeMessage;
648import sun.misc.BASE64Encoder;
649public class Prac5
650{
651 public static void main(String[] args)
652 {
653 Properties props = new Properties();
654 props.put("mail.smtp.starttls.enable", "true");
655 props.put("mail.smtp.host", "smtp.gmail.com");
656 props.put("mail.smtp.socketFactory.port", "587");
657 props.put("mail.smtp.socketFactory.class",
658 "javax.net.ssl.SSLSocketFactory");
659 props.put("mail.smtp.auth", "true");
660 props.put("mail.smtp.port", "587");
661 Session session = Session.getDefaultInstance(props,
662 new javax.mail.Authenticator()
663 {
664 protected PasswordAuthentication
665 getPasswordAuthentication()
666 {
667 return new
668 PasswordAuthentication("testmailid@gmail.com","secret");
669 }});
670 try
671 {
672 String msg="hello all!!!",cipherText,decryptedText;
673 KeyGenerator keyGen = KeyGenerator.getInstance("AES");
674 keyGen.init(128);
675 SecretKey secretKey = keyGen.generateKey();
676 Cipher aesCipher = Cipher.getInstance("AES");
677 aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
678 byte[] byteDataToEncrypt = msg.getBytes();
679 byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
680 cipherText = new BASE64Encoder().encode(byteCipherText);
681 Message message = new MimeMessage(session);
682 message.setFrom(new InternetAddress("testmailid@gmail.com"));
683 message.setRecipients(Message.RecipientType.TO,
684 InternetAddress.parse("receivermailid@gmail.com"));
685 message.setSubject("Testing Mail....");
686 message.setText(cipherText);
687 Transport.send(message);
688 System.out.println("Your mail has been sent!!!");
689 }
690 catch (Exception e)
691 {
692 System.out.println(e);
693 }
694 }
695}
696#+END_SRC
697* Practical 6
698** Aim
699#+BEGIN_VERSE
700Write a program to digitally sign MIME to create an ‘opaque’ signature.
701#+END_VERSE
702** Theory
703** Implementation
704*** GenerateKey.java
705#+BEGIN_SRC java
706package generatekey;
707import java.io.*;
708import java.security.*;
709import java.util.logging.Level;
710import java.util.logging.Logger;
711public class GenerateKey {
712 public static void main(String[] args)
713 {
714 BufferedReader br = new BufferedReader(new
715 InputStreamReader(System.in));
716 System.out.println("Enter the file name");
717 try
718 {
719 String f_name=br.readLine();
720 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
721 SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
722 keyGen.initialize(1024, random);
723 KeyPair pair = keyGen.genKeyPair();
724 PrivateKey priv = pair.getPrivate();
725 PublicKey pub = pair.getPublic();
726 Signature dsa = Signature.getInstance("SHA1withDSA");
727 dsa.initSign(priv);
728 FileInputStream fis = new FileInputStream (f_name);
729 BufferedInputStream bufin = new BufferedInputStream(fis);
730 byte [] buffer = new byte[1024];
731 int len;
732 while(bufin.available()!=0)
733 {
734 len=bufin.read(buffer);
735 dsa.update(buffer, 0, len);
736 }
737 bufin.close();
738 byte [] realSig = dsa.sign();
739 FileOutputStream sigfos = new FileOutputStream("sig");
740 sigfos.write(realSig);
741 sigfos.close();
742 byte [] key = pub.getEncoded();
743 FileOutputStream keyfos = new FileOutputStream("pub");
744 keyfos.write(key);
745 keyfos.close();
746 }
747 catch (Exception ex)
748 {
749 Logger.getLogger(GenerateKey.class.getName()).log(Level.SEVERE, null,
750 ex);
751 }
752 }
753}
754#+END_SRC
755*** VerifyKey.java
756#+BEGIN_SRC java
757package verifykey;
758import java.io.*;
759import java.security.*;
760import java.security.spec.X509EncodedKeySpec;
761import java.util.logging.Level;
762import java.util.logging.Logger;
763public class VerifyKey {
764 public static void main(String[] args)
765 {
766 try
767 {
768 BufferedReader br = new BufferedReader(new
769 InputStreamReader(System.in));
770 System.out.println("Enter the public key filename");
771 String pub = br.readLine();
772 System.out.println("Enter the Signature file");
773 String sigfile = br.readLine();
774 System.out.println("Enter the filename");
775 String f_name = br.readLine();
776 FileInputStream keyfis = new FileInputStream(pub);
777 byte [] encKey = new byte[keyfis.available()];
778 keyfis.read(encKey);
779 keyfis.close();
780 X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
781 KeyFactory keyfactory = KeyFactory.getInstance("DSA");
782 PublicKey pubKey = keyfactory.generatePublic(pubKeySpec);
783 FileInputStream sigfis =new FileInputStream(sigfile);
784 byte [] sigToVerify = new byte[sigfis.available()];
785 sigfis.read(sigToVerify);
786 sigfis.close();
787 Signature sig = Signature.getInstance("SHA1withDSA");
788 sig.initVerify(pubKey);
789 FileInputStream datafis = new FileInputStream(f_name);
790 BufferedInputStream bufin = new BufferedInputStream(datafis);
791 byte [] buffer = new byte[1024];
792 int len;
793 while(bufin.available()!=0){
794 len = bufin.read(buffer);
795 sig.update(buffer,0,len);
796 }
797 bufin.close();
798 boolean verfies = sig.verify(sigToVerify);
799 System.out.println("Signature verfies: "+verfies)
800 }
801 catch (Exception ex)
802 {
803 Logger.getLogger(VerifyKey.class.getName()).log(Level.SEVERE, null, ex);
804 }
805 }
806}
807#+END_SRC
808** Output
809*** GenerateKey
810#+BEGIN_VERSE
811Enter the filename
812myimage.jpg
813#+END_VERSE
814*** VerifyKey
815#+BEGIN_VERSE
816Enter the public key filename
817mypub
818Enter the Signature file
819sig
820Enter the filename
821myimage.jpg
822Signature verifies: true
823#+END_VERSE
824* Practical 7
825** Aim
826#+BEGIN_VERSE
827Write a program to generate DSA SSH key.
828#+END_VERSE
829** Theorem
830DSA (Digital Signature Algorithm) DSA is a variant on the ElGamal and Schnorr
831algorithms creates a 320 bit signature, but with 512-1024 bit security security
832again rests on difficulty of computing discrete logarithms has been quite widely
833accepted
834
835DSA Key Generation
836firstly shared global public key values (p,q,g) are chosen:
837choose a large prime p = 2 power L
838where L= 512 to 1024 bits and is a multiple of 64
839choose q, a 160 bit prime factor of p-1
840choose g = h power (p-1)/q
841for any h1
842then each user chooses a private key and computes their public key:
843choose x compute y = g power x(mod p)
844
845DSA key generation is related to, but somewhat more complex than El
846Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help
847speed up calculations and reduce the size of the resulting signature.
848** Implementation
849*** Export.java
850#+BEGIN_SRC java
851package export;
852import java.security.*;
853import java.security.spec.*;
854import java.io.*;
855public class Export
856{
857 public static void main(String args[])
858 {
859 try
860 {
861 KeyPairGenerator kpg=KeyPairGenerator.getInstance("DSA");
862 SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG",
863 "SUN");
864 kpg.initialize(1024,rnd);
865 KeyPair kp=kpg.generateKeyPair();
866 Class spec=Class.forName("java.security.spec.DSAPrivateKeySpec");
867 KeyFactory kf=KeyFactory.getInstance("DSA");
868 DSAPrivateKeySpecks=(DSAPrivateKeySpec)kf.getKeySpec(kp.getPriv
869 ate(),spec);
870 FileOutputStream fos = new
871 FileOutputStream("C:\\msc10\\exportedKey.txt");
872 ObjectOutputStream oos = new ObjectOutputStream(fos);
873 oos.writeObject(ks.getX());
874 oos.writeObject(ks.getP());
875 oos.writeObject(ks.getQ());
876 oos.writeObject(ks.getG());
877 System.out.println("Private Key Exported");
878 }
879 catch(Exception e)
880 {
881 e.printStackTrace();
882 }}}
883#+END_SRC
884*** Import.java
885#+BEGIN_SRC java
886package pkgimport;
887import java.security.*;
888import java.security.spec.*;
889import java.io.*;
890import java.math.*;
891public class Import
892{
893 public static void main(String args[])
894 {
895 try
896 {
897 FileInputStream fis = new FileInputStream("C:\\msc10\\exportedKey.txt");
898 ObjectInputStream ois= new ObjectInputStream(fis);
899 DSAPrivateKeySpec ks=new
900 DSAPrivateKeySpec((BigInteger)ois.readObject(),
901 (BigInteger)ois.readObject(),(BigInteger)ois.readObject(),
902 (BigInteger)ois.readObject());
903 KeyFactory kf=KeyFactory.getInstance("DSA");
904 PrivateKey pk=kf.generatePrivate(ks);
905 System.out.println("Got private Key");
906 }
907 catch(FileNotFoundException e)
908 {
909 System.out.println("Key not found");
910 }
911 catch(Exception e1)
912 {
913 System.out.println("Key is corrupted");
914 }}}
915
916#+END_SRC
917** Output
918*** Export
919#+BEGIN_VERSE
920Private Key Exported
921#+END_VERSE
922
923[[./op/p7-1.png]]
924
925*** Import
926#+BEGIN_VERSE
927Got Private Key
928#+END_VERSE
929[[./op/p7-2.png]]
930
931#+BEGIN_VERSE
932Key is corrupted
933#+END_VERSE