· 5 years ago · Feb 03, 2020, 04:06 AM
1BI
2Practical 1:
3Aim: Create table using different applications.
4Methods:
51] Using Excel Sheet (Pivot Table)
6Steps:
7Part 1:
8Open a new workbook and type the data as given
9Save the Workbook
10Part 2: (Creating Pivot table containing Department, Average Salary & Maximum Salary)
11Select the entire data [cell A1:D11]
12
13From the Insert Menu, Click on the Pivot table button and then select sub-option Pivot table
14The Pivot table’s dialog box appears as shown below, Accept the select range A1:D11. Click on “New Worksheet”
15
16
17In the Pivot table field list, click on Department and drag it to the Row Area
18In the Pivot table field list, click on the Salary field and drag it to the Value Area. It is displayed as “Sum of Salary”. Click on it and select value field settings
19
20
21
22Select the type of calculation as ‘Min’ and click on ‘OK’ to obtain minimum salary.
23Again drag the ‘Salary’ to value area. It is displayed as ‘Sum of salary’
24The completed Pivot table is displayed on the worksheet as shown below.
25Row Labels Min of Salary Sum of Salary
26Finance 25000 132000
27Marketing 39000 80000
28Production 25000 116000
29Grand Total 25000 328000
30
31Part 3: (Create Pivot table containing Joining Date, Sum of Salary and Minimum Salary)
32Select the entire data [cells A1:D11]
33From the Insert Menu. Click on the Pivot table button and then select sub-option Pivot table
34The Pivot tables dialog box appears as shown below.
35
36
37
38In the Pivot table field list, click on Join Date and drag it to the Row Area
39In the Pivot table field list, click on the Salary field and drag it to the Value Area. It is displayed as “Sum of Salary”, Click on it and select value field settings
40Select the type of calculation as ‘Min’ and click on ‘OK’ to obtain “Minimum of Salary”
41Again drag the ‘Salary’ to Value Area. It is displayed as “Sum of Salary”
42
43
44The completed Pivot table is displayed on the worksheet as shown below
45
46Row Labels Min of Salary Sum of Salary
4702-09-2006 40000 40000
4803-09-2006 25000 120000
4912-04-2007 37000 78000
5029-03-2008 25000 51000
5115-08-2008 39000 39000
52Grand Total 25000 328000
53
54
55
56
57
58
59
60
61Part 4: (Selecting Pivot table and Modifying its Properties)
62Click on cell A50 since it is the location of Pivot table
63Right click and select PivotTable options. It brings up the dialog box as shown below
64Select the Totals & Filters tab
65Deselect the option “Show grand total for columns” and click ‘OK’.
66
67
68
69The Pivot table changes in the following manner:
70
71Row Labels Min of Salary Sum of Salary
7202-09-2006 40000 40000
7303-09-2006 25000 120000
7412-04-2007 37000 78000
7529-03-2008 25000 51000
7615-08-2008 39000 39000
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104Practical 2:
105Aim: Develop an application to design a warehouse by importing various tables from external source.
106Description:
107Creating a DTS Package with the DTS Import/Export Wizard.
108The Data Transformation Services (DTS) Import / Export Wizard offers the simplest method of building a DTS package. Interactively guiding through the process of copying and transforming data.
109
110Following are the steps for creating a package with the DTS Import / Export Wizard.
111Steps:
112Open SQL Server Enterprise Manager, expand the server and click the Database folder.
113
114
115On the Tools menu, point to Data Transformation Services, and then click Import Data
116
117
118In the Choose Data Source dialog box, select Microsoft Access as the Data Source and then type the path and file name of your Access Database (.mdb) or use the browser to browse the file
119
120In the Choose Destination dialog box, select Microsoft OLE DB Provider for SQL Server, and then select the database server and the required authentication mode. In the Database dialog box, select the target database on the server.
121
122In the Specify Table Copy or Query dialog box, click Copy tables and views from the source database. If you copy the data or the results of a query, you can customize the data being copied to the destination. You can:
123Select which source or destination columns to copy.
124Select which source or destination columns to ignore.
125Change the data type where valid.
126Define how the data is to be converted between source and destination.
127
128
129
130In the Select Source Tables and Views dialog box, select the tables and queries to import.
131
132In the Save, Schedule, and Replicate Package dialog box, select Run Immediately.
133
134
135
136
137
138
139
140Click Finish
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165Practical 3:
166Aim: Develop an application to creating a fact table and measures in a cube.
167Description:
168Create a new OLAP Database:
169Open Programs -> Microsoft SQL Server -> Analysis Services -> Analysis Manager.
170Right Click the server in the console tree and click New Database to display the Databases Dialog Box.
171Type Sales as the database name and type Market Database as the description.
172Click OK to close the dialog box and to create the database.
173
174
175Specifying a Data Source:
176Expand the Sales database folder. Right click the Data Source folder and on the shortcut menu click New Data Source.
177Select Microsoft Jet 4.0 OLE DB Provider and click Next
178
179On the Connection Tab of the Data Link Properties dialog box, click the ellipsis button (…), navigate to the folder containing the Sales.mdb
180Click Test Connection to make sure the data source destination is correct and then click OK to close the dialog box. Expand the Data Sources folder to see the New Data Source
181
182
183
184
185Designing a Cube by Using the Cube Wizard
186Select the Fact Tables and the Measures:
187Right Click the Cube folder under the Sales database, point to New Cube and then click Wizard to start the Cube Wizard. On the Welcome screen, click Next.
188
189Select SalesFact from the list of tables
190
191
192Click Browse Data to review the records in the table. Close the Browse Data Window.
193
194After Selecting the Fact table, click Next to move to the next step of the wizard.
195Add the Quantity and Sales columns as measures by double clicking each in turn. You can select a measure and click the right arrow button (>)
196
197After adding both measures, Click Next.
198Practical 4:
199Aim: Develop an application to design a dimension tables in cube and form a star schema.
200Description:
201Create a Dimension from a Star Schema table:
202Click a New Dimension in the wizard to start the Dimension Wizard. Select the option to skip the welcome screen and then click on Next.
203
204
205Click the option Star Schema: A Single Dimension Table and click Next.
206
207
208
209In the select “The Dimension Table Screen”, select Store from the Available Tables list
210
211After selecting the dimension table, Click Next.
212Double-click Country, City in the order. You can select the levels from the most summarized to the most detailed.
213
214Click Next three times. Type State as the name of the dimension. Before closing the wizard you can preview the dimension hierarchy.
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243PRACTICAL NO:5
244Title: Cube Creation
245Problem Statement: Create an dimension table in a cube and form snow flake schema
246Description:
247Create a dimension from Snowflake schema tables:
248Click Next Dimension in the Cube wizard to again launch the Dimension Wizard.
249Click the option “Snowflake Schema: Multiple, Related Dimension Tables”, and Click Next.
250Double-click the dimension tables in the following order: Product, Product Subcategory, and Product Category.
251
252
253Click Next.
254
255Review the joins between tables. If necessary add join between the two Subcategory_ID columns and the two Category_ID columns, and click Next.
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280Double-click Category, Product_Name, and Subcategory intentionally reversing the order of the last two levels. The Dimension Wizard displays a message suggesting that you can rearrange the levels.
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307Click Yes to put the Product_Name level below the Subcategory level.
308
309Click Next three times.
310
311Type Product as the name of the dimension, expand items in the Preview window as desired, and click Finish.
312
313Practical no:6
314Aim : Create an dimension table in a cube and form Parent Child schema
315Create a dimension from Parent-Child tables:
316Click Next Dimension in the Cube wizard to again launch the Dimension Wizard.
317
318Click Parent-Child: Two Related Columns In a Single Dimension Table, and click Next.
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355Click Next twice: once after defining the parent-child hierarchy, and once to bypass the advanced options step.
356Type Employee as the name of the dimension.
357Click Finish.
358
359
360
361Practical No: 7
362AIM: Develop an application to demonstrate operations like roll-up, drill-down, slice, and dice.
363STEP: To go to shared dimension and select new cube with parent child schema
364
365Select Advance Option
366
367In Dimension Wizard Set custom rollups
368
369
370
371
372
373Specify ordering and uniqueness:
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391Practical 8:
392AIM: Develop an application to demonstrate processing and browsing data from a cube.
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418BROWSING DATA
419
420
421
422
423
424
425
426
427
428
429
430
431Practical:-9
432AndroidManifest.xml
433<?xml version="1.0" encoding="utf-8"?>
434<manifest xmlns:android="http://schemas.android.com/apk/res/android"
435 package="com.hit.lenovo">
436 <application
437 android:allowBackup="true"
438 android:icon="@mipmap/ic_launcher"
439 android:label="@string/app_name"
440 android:roundIcon="@mipmap/ic_launcher_round"
441 android:supportsRtl="true"
442 android:theme="@style/AppTheme">
443 <activity android:name=".MainActivity">
444 <intent-filter>
445 <action android:name="android.intent.action.MAIN" />
446 <category android:name="android.intent.category.LAUNCHER" />
447 </intent-filter>
448 </activity>
449 </application>
450</manifest>
451
452MainActivity.java
453
454package com.hit.lenovo;
455
456import android.annotation.SuppressLint;
457import android.os.Bundle;
458import android.support.v7.app.AppCompatActivity;
459import android.widget.TextView;
460import android.widget.Toast;
461
462public class MainActivity extends AppCompatActivity {
463 private int Count;
464 private TextView print;
465
466 @SuppressLint("SetTextI18n")
467 @Override
468 protected void onCreate(Bundle savedInstanceState) {
469 super.onCreate(savedInstanceState);
470 setContentView(R.layout.activity_main);
471 Count = 1;
472 print = findViewById(R.id.print);
473 print.setText(print.getText().toString() + Count + ". onCreate Called\n");
474 }
475
476 @SuppressLint("SetTextI18n")
477 @Override
478 protected void onStart() {
479 super.onStart();
480 Count = Count + 1;
481 print.setText(print.getText().toString() + Count + ". onStart Called\n");
482 Toast.makeText(getApplicationContext(), "Start Method Called", Toast.LENGTH_LONG).show();
483
484 }
485
486 @SuppressLint("SetTextI18n")
487 @Override
488 protected void onPause() {
489 super.onPause();
490 Count = Count + 1;
491 print.setText(print.getText().toString() + Count + ". onPause Called\n");
492 Toast.makeText(getApplicationContext(), "Pause Method Called", Toast.LENGTH_LONG).show();
493
494 }
495
496 @SuppressLint("SetTextI18n")
497 @Override
498 protected void onResume() {
499 super.onResume();
500 Count = Count + 1;
501 print.setText(print.getText().toString() + Count + ". onResume Called\n");
502 Toast.makeText(getApplicationContext(), "Resume Method Called", Toast.LENGTH_LONG).show();
503
504 }
505
506 @SuppressLint("SetTextI18n")
507 @Override
508 protected void onStop() {
509 super.onStop();
510 Count = Count + 1;
511 print.setText(print.getText().toString() + Count + ". onStop Called\n");
512 Toast.makeText(getApplicationContext(), "Stop Method Called", Toast.LENGTH_LONG).show();
513
514 }
515
516 @SuppressLint("SetTextI18n")
517 @Override
518 protected void onPostResume() {
519 super.onPostResume();
520 Count = Count + 1;
521 print.setText(print.getText().toString() + Count + ". onPostResume\n");
522 Toast.makeText(getApplicationContext(), "PostResume Called", Toast.LENGTH_LONG).show();
523 }
524
525 @SuppressLint("SetTextI18n")
526 @Override
527 protected void onDestroy() {
528 Count = Count + 1;
529 print.setText(print.getText().toString() + Count + ". onDestroy Called\n");
530 Toast.makeText(getApplicationContext(), "Destroy Method Called", Toast.LENGTH_LONG).show();
531 super.onDestroy();
532 }
533
534 @SuppressLint("SetTextI18n")
535 @Override
536 protected void onRestart() {
537 super.onRestart();
538 Count = Count + 1;
539 print.setText(print.getText().toString() + Count + ". onRestart Called\n");
540 Toast.makeText(getApplicationContext(), "onRestart Called", Toast.LENGTH_LONG).show();
541
542 }
543
544}
545activity_main.xml
546
547<?xml version="1.0" encoding="utf-8"?>
548<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
549 android:id="@+id/activity_main"
550 android:layout_width="match_parent"
551 android:layout_height="match_parent">
552 <TextView
553 android:layout_width="match_parent"
554 android:layout_height="wrap_content"
555 android:gravity="center"
556 style="@style/TextAppearance.AppCompat.Large"
557 android:id="@+id/output" />
558</RelativeLayout>
559
560OUTPUT
561
562
563
564
565
566Practical No 10
567
568Manifest.xml
569<?xml version="1.0" encoding="utf-8"?>
570<manifest xmlns:android="http://schemas.android.com/apk/res/android"
571 package="com.hit.lenovo">
572 <application
573 android:allowBackup="true"
574 android:icon="@mipmap/ic_launcher"
575 android:label="@string/app_name"
576 android:roundIcon="@mipmap/ic_launcher_round"
577 android:supportsRtl="true"
578 android:theme="@style/AppTheme">
579 <activity android:name=".MainActivity">
580 <intent-filter>
581 <action android:name="android.intent.action.MAIN" />
582 <category android:name="android.intent.category.LAUNCHER" />
583 </intent-filter>
584 </activity>
585 </application>
586</manifest>
587
588activity_main.xml
589<?xml version="1.0" encoding="utf-8"?>
590<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
591 xmlns:tools="http://schemas.android.com/tools"
592 android:id="@+id/activity_main"
593 android:layout_width="match_parent"
594 android:layout_height="match_parent">
595
596 <RelativeLayout
597 android:layout_width="match_parent"
598 android:layout_height="match_parent">
599
600 <RelativeLayout
601 android:id="@+id/out_rel"
602 android:layout_width="match_parent"
603 android:layout_height="wrap_content"
604 android:layout_alignParentLeft="false"
605 android:layout_alignParentStart="false"
606 android:background="#fff"
607 android:visibility="gone">
608
609 <TextView
610 android:id="@+id/output_test"
611 android:layout_width="wrap_content"
612 android:layout_height="wrap_content" />
613
614 </RelativeLayout>
615
616 <RelativeLayout
617 android:id="@+id/shared_rel"
618 android:layout_width="match_parent"
619 android:layout_height="wrap_content"
620 android:layout_below="@+id/out_rel"
621 android:layout_marginTop="16dp">
622
623 <TextView
624 android:id="@+id/shared_pref_text"
625 android:layout_width="wrap_content"
626 android:layout_height="wrap_content"
627 android:padding="5dp"
628 android:layout_marginStart="10dp"
629 android:text="Save In SharedPreferences" />
630
631 <EditText
632 android:id="@+id/shared_pref_edit"
633 android:layout_width="match_parent"
634 android:layout_height="wrap_content"
635 android:background="@drawable/edittext_bg"
636 android:layout_margin="10dp"
637 android:padding="5dp"
638 android:layout_below="@id/shared_pref_text" />
639
640 <Button
641 android:id="@+id/save_sharedpref_button"
642 android:layout_width="wrap_content"
643 android:layout_height="wrap_content"
644 android:layout_alignParentEnd="true"
645 android:layout_below="@+id/shared_pref_edit"
646 android:onClick="sharedButtonClick"
647 android:padding="5dp"
648 android:layout_marginEnd="5dp"
649 android:textColor="@color/black"
650 android:text="Save In Shared Preferences" />
651
652 </RelativeLayout>
653
654 <RelativeLayout
655 android:id="@+id/internalstore_rel"
656 android:layout_width="match_parent"
657 android:layout_height="wrap_content"
658 android:layout_below="@+id/shared_rel"
659 android:layout_marginTop="16dp">
660
661 <TextView
662 android:id="@+id/internal_storage_text"
663 android:layout_width="wrap_content"
664 android:layout_height="wrap_content"
665 android:padding="5dp"
666 android:layout_marginStart="10dp"
667 android:text="Save In Internal Storage" />
668
669 <EditText
670 android:id="@+id/internal_storage_edit"
671 android:layout_width="match_parent"
672 android:layout_height="wrap_content"
673 android:background="@drawable/edittext_bg"
674 android:layout_margin="10dp"
675 android:padding="5dp"
676 android:layout_below="@+id/internal_storage_text" />
677
678 <Button
679 android:id="@+id/save_internal_button"
680 android:layout_width="wrap_content"
681 android:layout_height="wrap_content"
682 android:padding="5dp"
683 android:layout_marginEnd="5dp"
684 android:textColor="@color/black"
685 android:layout_alignParentEnd="true"
686 android:layout_below="@+id/internal_storage_edit"
687 android:onClick="internalButtonClick"
688 android:text="Save In Internal Storage" />
689
690 </RelativeLayout>
691
692 <RelativeLayout
693 android:id="@+id/externalstore_rel"
694 android:layout_width="match_parent"
695 android:layout_height="wrap_content"
696 android:layout_below="@+id/internalstore_rel"
697 android:layout_marginTop="16dp">
698
699 <TextView
700 android:id="@+id/external_storage_text"
701 android:layout_width="wrap_content"
702 android:layout_height="wrap_content"
703 android:padding="5dp"
704 android:layout_marginStart="10dp"
705 android:text="Save In External Storage" />
706
707 <EditText
708 android:id="@+id/external_storage_edit"
709 android:layout_width="match_parent"
710 android:layout_height="wrap_content"
711 android:background="@drawable/edittext_bg"
712 android:layout_margin="10dp"
713 android:padding="5dp"
714 android:layout_below="@+id/external_storage_text" />
715
716 <Button
717 android:id="@+id/save_external_button"
718 android:layout_width="wrap_content"
719 android:layout_height="wrap_content"
720 android:layout_alignParentEnd="true"
721 android:layout_below="@+id/external_storage_edit"
722 android:onClick="externalButtonClick"
723 android:padding="5dp"
724 android:layout_marginEnd="5dp"
725 android:textColor="@color/black"
726 android:text="Save In External Storage" />
727
728 </RelativeLayout>
729
730 <RelativeLayout
731 android:id="@+id/sqlstore_rel"
732 android:layout_width="match_parent"
733 android:layout_height="wrap_content"
734 android:layout_below="@+id/externalstore_rel"
735 android:layout_marginTop="16dp">
736
737 <TextView
738 android:id="@+id/sql_storage_text"
739 android:layout_width="wrap_content"
740 android:layout_height="wrap_content"
741 android:padding="5dp"
742 android:layout_marginStart="10dp"
743 android:text="Save In SQLLITE Storage" />
744
745 <Button
746 android:id="@+id/save_sql_button"
747 android:layout_width="wrap_content"
748 android:layout_height="wrap_content"
749 android:layout_alignParentRight="true"
750 android:layout_below="@+id/sql_storage_edit"
751 android:onClick="sqlDBButtonClick"
752 android:padding="5dp"
753 android:layout_marginEnd="5dp"
754 android:textColor="@color/black"
755 android:text="Save In Sql database" />
756
757 <EditText
758 android:id="@+id/sql_storage_edit"
759 android:layout_width="match_parent"
760 android:layout_height="wrap_content"
761 android:layout_alignParentLeft="true"
762 android:layout_alignParentStart="true"
763 android:background="@drawable/edittext_bg"
764 android:layout_margin="10dp"
765 android:padding="5dp"
766 android:layout_below="@+id/sql_storage_text"
767 tools:ignore="RtlHardcoded" />
768
769 </RelativeLayout>
770 </RelativeLayout>
771
772</ScrollView>
773
774edittext_bg.xml
775<?xml version="1.0" encoding="utf-8"?>
776<shape xmlns:android="http://schemas.android.com/apk/res/android">
777
778 <!-- Background Color -->
779 <solid android:color="@android:color/transparent" />
780 <corners android:radius="5dp" />
781 <!-- Border Color -->
782 <stroke
783 android:width="1dp"
784 android:color="@color/darkgary" />
785
786</shape>
787
788
789
790
791MainActivity.java
792
793package com.hit.lenovo;
794
795import android.annotation.SuppressLint;
796import android.content.Context;
797import android.content.SharedPreferences;
798import android.database.Cursor;
799import android.database.sqlite.SQLiteDatabase;
800import android.os.Bundle;
801import android.os.Environment;
802import android.support.v7.app.AppCompatActivity;
803import android.util.Log;
804import android.view.View;
805import android.widget.EditText;
806import android.widget.RelativeLayout;
807import android.widget.TextView;
808import android.widget.Toast;
809
810import java.io.BufferedReader;
811import java.io.File;
812import java.io.FileInputStream;
813import java.io.FileOutputStream;
814import java.io.IOException;
815import java.io.InputStreamReader;
816
817public class MainActivity extends AppCompatActivity {
818 SharedPreferences tcscpref;
819 SharedPreferences.Editor tcsceditor;
820 private String TAG = "MainActivity";
821 private SQLiteDatabase mydb;
822
823 @SuppressLint("CommitPrefEdits")
824 @Override
825 protected void onCreate(Bundle savedInstanceState) {
826 super.onCreate(savedInstanceState);
827 setContentView(R.layout.activity_main);
828 tcscpref = getSharedPreferences("tcsc", MODE_PRIVATE);
829 tcsceditor = tcscpref.edit();
830 mydb = openOrCreateDatabase("TCSCSQLDB", MODE_PRIVATE, null);
831 viewFile();
832 }
833
834 public void sharedButtonClick(View v) {
835 EditText sharedPrefET = (EditText) findViewById(R.id.shared_pref_edit);
836 String textToStore = sharedPrefET.getText().toString();
837 tcsceditor.putString("user_text", textToStore);
838 tcsceditor.commit();
839 Toast.makeText(getApplicationContext(), "Saved in The Shared Pref.", Toast.LENGTH_SHORT).show();
840 }
841
842 public void internalButtonClick(View v) {
843 EditText internalStoreET = findViewById(R.id.internal_storage_edit);
844 String textToStore = internalStoreET.getText().toString();
845 try {
846 FileOutputStream fos = openFileOutput("user_txtfile.txt", Context.MODE_PRIVATE);
847 fos.write(textToStore.getBytes());
848 fos.flush();
849 fos.close();
850 viewFile();
851 Toast.makeText(getApplicationContext(), "Saved in Internal Dir", Toast.LENGTH_SHORT).show();
852 } catch (IOException ioe) {
853 Log.e(TAG, "IOE Err : " + ioe.getLocalizedMessage());
854 }
855 }
856
857 public void externalButtonClick(View v) {
858 if (isExternalStorageReadable() && isExternalStorageWritable()) {
859 EditText externalStoreET = findViewById(R.id.external_storage_edit);
860 String textToStore = externalStoreET.getText().toString();
861 try {
862 String externalDir = Environment.getExternalStorageDirectory().toString();
863 File myDir = new File(externalDir + File.separator + "Newfolder");
864 myDir.mkdirs();
865 String fname = "user_txtfile.txt";
866 File nfile = new File(myDir, fname);
867 if (nfile.exists())
868 nfile.delete();
869 FileOutputStream fos = new FileOutputStream(nfile);
870 fos.write(textToStore.getBytes());
871 fos.flush();
872 fos.close();
873 viewFile();
874 Toast.makeText(getApplicationContext(), "Saved in External Dir", Toast.LENGTH_LONG).show();
875 } catch (IOException ioe) {
876 Log.e(TAG, "IOE Err : " + ioe.getLocalizedMessage());
877 }
878 } else {
879 Toast.makeText(getApplicationContext(), "Sorry no External Storage Detected", Toast.LENGTH_LONG).show();
880 }
881 }
882
883 public void sqlDBButtonClick(View v) {
884 try {
885 EditText externalStoreET = (EditText) findViewById(R.id.sql_storage_edit);
886 String textToStore = externalStoreET.getText().toString();
887
888 mydb.execSQL("DROP TABLE IF EXISTS USERTEXTTABLE");
889 mydb.execSQL("CREATE TABLE USERTEXTTABLE(USERTEXT VARCHAR);");
890 String query = "INSERT INTO USERTEXTTABLE VALUES ('" + textToStore + "');";
891 mydb.execSQL(query);
892 Toast.makeText(getApplicationContext(), "Saved in SQL DB", Toast.LENGTH_LONG).show();
893 viewFile();
894
895 } catch (Exception ioe) {
896 Log.e(TAG, "IOE Err : " + ioe.getLocalizedMessage());
897 }
898 }
899
900 @SuppressLint("SetTextI18n")
901 private void viewFile() {
902 try {
903
904 RelativeLayout rel = (RelativeLayout) findViewById(R.id.out_rel);
905 rel.setVisibility(View.VISIBLE);
906 FileInputStream infis = openFileInput("user_txtfile.txt");
907 BufferedReader inbufferedReader = new BufferedReader(new InputStreamReader(infis, "UTF-8"));
908 StringBuilder insb = new StringBuilder();
909 String inline;
910 while ((inline = inbufferedReader.readLine()) != null) {
911 insb.append(inline);
912 }
913 String fname = "user_txtfile.txt";
914 File exfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Newfolder" + File.separator + fname);
915 FileInputStream exfis = new FileInputStream(exfile);
916 BufferedReader exbufferedReader = new BufferedReader(new InputStreamReader(exfis, "UTF-8"));
917 StringBuilder exsb = new StringBuilder();
918 String exline;
919 while ((exline = exbufferedReader.readLine()) != null) {
920 exsb.append(exline);
921 }
922 String note = "";
923 try {
924 String query = "select USERTEXT from USERTEXTTABLE";
925 Cursor resultSet = mydb.rawQuery(query, null);
926 resultSet.moveToPosition(0);
927 Log.e(TAG, "" + resultSet.getColumnName(0));
928 Log.e(TAG, "" + resultSet.getColumnCount());
929 Log.e(TAG, "" + resultSet.getCount());
930 Log.e(TAG, "done : " + resultSet.getString(0));
931 note = resultSet.getString(0);
932 } catch (Exception e) {
933 Log.e(TAG, "SQL View Err : " + e.getLocalizedMessage());
934 }
935 TextView outputTV = (TextView) findViewById(R.id.output_test);
936 outputTV.setText("Shared : " + tcscpref.getString("user_text", "Can't Find") + "\nInternal : " + insb.toString() + "\nExternal : " + exsb.toString() + "\nSQLLITE : " + note);
937 } catch (IOException e) {
938 Log.e(TAG, "" + e.getLocalizedMessage());
939 }
940 }
941
942 public boolean isExternalStorageWritable() {
943 String state = Environment.getExternalStorageState();
944 if (Environment.MEDIA_MOUNTED.equals(state)) {
945 return true;
946 } return false;
947 }
948 public boolean isExternalStorageReadable() {
949 String state = Environment.getExternalStorageState();
950 if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
951 return true;
952 }
953 return false;
954 }
955
956}
957
958OUTPUT
959
960
961
962
963 CYBER
964
965
966
967Practical 1:
968Aim: Write a program to store username and password in an encrypted form in a database to implement integrity lock.
969
970Code:
971
972Frame.java
973
974import java.sql.Connection;
975import java.sql.DriverManager;
976import java.sql.PreparedStatement;
977import java.sql.SQLException;
978import java.util.Arrays;
979import java.util.logging.Level;
980import java.util.logging.Logger;
981import javax.crypto.Cipher;
982import javax.crypto.KeyGenerator;
983import javax.crypto.SecretKey;
984import javax.swing.JOptionPane;
985
986public class Frame extends javax.swing.JFrame {
987 Cipher cipher;
988 SecretKey key;
989 Connection con;
990
991 public Frame() {
992 initComponents();
993 }
994
995 private void InsertActionPerformed(java.awt.event.ActionEvent evt) {
996 try
997 {
998 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
999 con = DriverManager.getConnection("jdbc:odbc:duke");
1000 con.setAutoCommit(false);
1001 cipher = Cipher.getInstance("DESede");
1002 key = KeyGenerator.getInstance("DESede").generateKey();
1003 String username = "root";
1004 String password = "";
1005 byte[] uname = encrypt(username);
1006 byte[] pass = encrypt(password);
1007
1008 String query = "insert into cyber values(?,?)";
1009 PreparedStatement ps = con.prepareStatement(query);
1010 ps.setBytes(1,uname);
1011 ps.setBytes(2,pass);
1012 System.out.println("Encrypted username is:"+uname);
1013 System.out.println("Encrypted password is:"+pass);
1014 ps.executeUpdate();
1015 con.commit();
1016
1017 JOptionPane.showMessageDialog(rootPane,"User Inserted Successfully","Successful",JOptionPane.INFORMATION_MESSAGE);
1018 }
1019 catch(Exception e)
1020 {
1021 try
1022 {
1023 con.rollback();
1024 }
1025 catch (SQLException ex)
1026 {
1027 Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
1028 }
1029 }
1030
1031 }
1032
1033 private byte[] encrypt(String data)
1034{
1035 byte[] encryptedString=null;
1036 try
1037 {
1038 cipher.init(Cipher.ENCRYPT_MODE,key);
1039 encryptedString = cipher.doFinal(data.getBytes());
1040 }
1041 catch(Exception e)
1042 {
1043 e.printStackTrace();
1044 }
1045 return encryptedString;
1046
1047 }
1048
1049 public static void main(String args[]) {
1050 java.awt.EventQueue.invokeLater(new Runnable() {
1051 public void run() {
1052 new Frame().setVisible(true);
1053 }
1054 });
1055
1056
1057 }
1058
1059 // Variables declaration - do not modify
1060 private javax.swing.JButton Insert;
1061 private javax.swing.JLabel jLabel1;
1062 private javax.swing.JLabel jLabel2;
1063 private javax.swing.JTextField jTextField1;
1064 private javax.swing.JTextField jTextField2;
1065 // End of variables declaration
1066}
1067Output:
1068
1069
1070
1071
1072
1073Table Schema & Values:
1074
1075
1076
1077
1078
1079
1080
1081
1082Practical 2:
1083Aim: Write SQL query to retrieve sensitive information from less sensitive queries.
1084
1085
1086A] Table Creation
1087create table student
1088(
1089 name varchar2(20),
1090 sex varchar2(20),
1091 race varchar2(20),
1092 aid number(10),
1093 fines number(10),
1094 drugs number(10),
1095 dorm varchar2(20)
1096);
1097
1098B] Records Inserted in STUDENT Table
1099INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Adams', 'M', 'C', 5000, 45, 1,'West');
1100INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Bailey', 'M', 'B', 0, 0, 0,'Grey');
1101INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Chin', 'F', 'A', 3000, 20, 0,'West');
1102INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Dewitt', 'M', 'B', 1000, 35, 3,'Grey');
1103INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Earhart', 'F', 'C', 2000, 95, 1,'Holmes');
1104INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Fein', 'F', 'C', 1000, 15, 0,'West');
1105INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Groff', 'M', 'C', 4000, 0, 3,'West');
1106INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Hill', 'F', 'B', 5000, 10, 2,'Holmes');
1107INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Koch', 'F', 'C', 0, 0, 1,'West');
1108INSERT INTO student (name, sex, race, aid, fines, drugs, dorm) VALUES ('Liu', 'F', 'A', 0, 10, 2,'Grey');
1109
1110
1111
1112Queries:
1113Direct Attack
1114Display names of males having drug count as 1.
1115select name from student where drugs=1 and sex='M';
1116
1117Display names of males where drug count is 1 or dorm is Aryes.
1118select name from student where (drugs=1 and sex='M') or dorm='Aryes';
1119
1120
1121
1122
1123
1124
1125Indirect Attack:
1126Find student aid total by sex and dorm.
1127select aid from student where sex='M' and dorm='Holmes';
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148select sum(aid) from student where sex='F' and dorm='Holmes';
1149
1150
1151select sum(aid) from student where dorm='Holmes';
1152
1153
1154select sum(aid) from student where sex='M' and dorm='Grey';
1155
1156
1157
1158select sum(aid) from student where sex='F' and dorm='Grey';
1159
1160
1161select sum(aid) from student where dorm='Grey';
1162
1163
1164select sum(aid) from student where sex='M' and dorm='West';
1165
1166
1167
1168select sum(aid) from student where sex='F' and dorm='West';
1169
1170
1171select sum(aid) from student where dorm='West';
1172
1173
1174select sum(aid) from student where sex='M' and (dorm='Holmes' or dorm='Grey' or dorm='West');
1175
1176
1177
1178select sum(aid) from student where sex='F' and (dorm='Holmes' or dorm='Grey' or dorm='West');
1179
1180
1181select sum(aid) from student where (sex='F' or sex='M') and (dorm='Holmes' or dorm='Grey' or dorm='West');
1182
1183
1184Find student aid total by sex and dorm.
1185select count(sex) from student where sex='M' and dorm='Holmes';
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208select count(sex) from student where sex='F' and dorm='Holmes';
1209
1210
1211select count(sex) from student where dorm='Holmes';
1212
1213
1214
1215
1216select count(sex) from student where sex='M' and dorm='Grey';
1217
1218
1219select count(sex) from student where sex='F' and dorm='Grey';
1220
1221
1222select count(sex) from student where dorm='Grey';
1223
1224
1225
1226select count(sex) from student where sex='M' and dorm='West';
1227
1228
1229select count(sex) from student where sex='F' and dorm='West';
1230
1231
1232select count(sex) from student where dorm='West';
1233
1234
1235
1236
1237
1238select count(sex) from student where sex='M' and (dorm='West' or dorm='Grey' or dorm='Holmes');
1239
1240
1241select count(sex) from student where sex='F' and (dorm='West' or dorm='Grey' or dorm='Holmes');
1242
1243
1244select count(sex) from student where (sex='F' or sex='M') and (dorm='West' or dorm='Grey' or dorm='Holmes');
1245
1246
1247Find names of student.
1248select name from student where sex='M' and dorm='Holmes';
1249
1250
1251select name from student where sex='M' and dorm='West';
1252
1253
1254select name from student where sex='F' and dorm='Grey';
1255
1256Tracker Attack:
1257Display AID from Students where Sex=’M’ and Drugs=2 group by Aid.
1258select (select sum(aid) from student where sex='M')-(select sum(aid) from student where sex='M' and ((sex='M' and drugs<>2) or (sex<>'M' and sex<>'F'))) "AID" from dual;
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273Display how many females with Race as Caucasians live in dorm as Holmes.
1274select ((select count(sex) from student where sex='F') - (select count(sex) from student where sex='F' and dorm='Holmes')) from dual;
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330Practical 3:
1331Aim: Write SQL query to create a view to implement concept of views and commutative filter in distributed databases.
1332Login:system, Password:tiger, Hoststring:tcsc
1333create user u1 identified by secret1;
1334grant create session,create table,create sequence,create view to u1;
1335grant connect,resource to u1;
1336create user u2 identified by secret2;
1337grant create session,create table,create sequence,create view to u2;
1338grant connect,resource to u2;
1339create user u3 identified by secret3;
1340grant create session,create table,create sequence,create view to u3;
1341grant connect,resource to u3;
1342
1343
1344
1345
1346
1347
1348
1349Login:scott, Password:tiger, Hoststring:tcsc
1350create table emp17
1351(
1352 eno number(5),
1353 ename varchar2(20),
1354 address varchar2(50),
1355 email varchar2(40),
1356 sal number(8)
1357 );
1358insert into emp17(eno, ename, address, email, sal) values(101, ‘Simran’, ‘Ghatkopar’, ’sk@gmail.com’, 50000);
1359insert into emp17(eno, ename, address, email, sal) values(102, ‘Harshada’, ‘Vikroli’, ’hs@gmail.com’, 48000);
1360insert into emp17(eno, ename, address, email, sal) values(103, ‘Jyoti’, ‘Thane’, ’jv@gmail.com’, 30000);
1361insert into emp17(eno, ename, address, email, sal) values(104, ‘Ritu’, ‘Sion’, ’rp@gmail.com’, 55000);
1362insert into emp17(eno, ename, address, email, sal) values(105, ‘Asees’, ‘Andheri', ’ag@gmail.com’, 50000);
1363select * from emp17;
1364
1365
1366
1367
1368Login:u1, Password:secret1, Hoststring:tcsc
1369create database link user1 connect to scott identified by tiger using 'tcsc';
1370create table emp1 as select eno,ename,address from emp17@user1;
1371select * from emp1;
1372
1373
1374Login:u2, Password:secret2, Hoststring:tcsc
1375create database link user2 connect to scott identified by tiger using 'tcsc';
1376create table emp2 as select eno,email,sal from emp17@user2;
1377select * from emp2;
1378
1379
1380Login:u3, Password:secret3, Hoststring:tcsc
1381create database link user3 connect to u1 identified by secret1 using 'tcsc';
1382create database link user_03 connect to u2 identified by secret2 using 'tcsc';
1383create view v as select e1.eno,e1.ename,e1.address,e2.email from emp1@user3 e1, emp2@user_03 e2 where e1.eno=e2.eno;
1384
1385
1386Select * from v;
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411Practical No:4
1412
1413Aim: Write a program to implement SSL
1414Steps Involved:
1415
1416Write the following command on command prompt:
1417keytool -genkey -keystore mySrvKeystore -keyalg RSA
1418(It will ask for password give password as secret & provide other info when it asks password for mykey press enter).
1419
1420
1421
1422Create a Java Application (Server program in Netbeans)
1423Copy mySrvKeystore file & paste into server folder.
1424Right click on project->properties & make following changes under Run tab:
1425Working Directory should be set to current directory
1426Write the following in VM Options:
1427-Djavax.net.ssl.keyStore=mySrvKeystore
1428-Djavax.net.ssl.keyStorePassword=secret
1429
1430Code:
1431
1432SSLServer.java
1433
1434package sslserver;
1435import javax.net.ssl.SSLServerSocket;
1436import javax.net.ssl.SSLServerSocketFactory;
1437import javax.net.ssl.SSLSocket;
1438import java.io.BufferedReader;
1439import java.io.InputStreamReader;
1440
1441public class SSLServer
1442{
1443 public static void main(String[] args)
1444 {
1445 try
1446 {
1447 SSLServerSocketFactory fac =(SSLServerSocketFactory)
1448 SSLServerSocketFactory.getDefault();
1449 SSLServerSocket ser_soc = (SSLServerSocket)
1450 fac.createServerSocket(9999);
1451 SSLSocket ssl_soc = (SSLSocket) ser_soc.accept();
1452 BufferedReader br = new BufferedReader(new
1453 InputStreamReader(ssl_soc.getInputStream()));
1454 String s = null;
1455 while ((s = br.readLine()) != null)
1456 {
1457 System.out.println(s);
1458 System.out.flush();
1459 }
1460 }
1461 catch (Exception e)
1462 {
1463 e.printStackTrace();
1464 }
1465 }
1466}
1467
1468SSLClient.java
1469
1470package sslclient;
1471import java.io.BufferedReader;
1472import java.io.BufferedWriter;
1473import java.io.InputStreamReader;
1474import java.io.OutputStreamWriter;
1475import javax.net.ssl.SSLSocket;
1476import javax.net.ssl.SSLSocketFactory;
1477
1478public class SSLClient
1479{
1480 public static void main(String[] args)
1481 {
1482 try
1483 {
1484 SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
1485 SSLSocket ssl_soc = (SSLSocket) fac.createSocket("localhost", 9999);
1486 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
1487 BufferedWriter bw= new BufferedWriter( new OutputStreamWriter(ssl_soc.getOutputStream()));
1488 String s = null;
1489 while ((s = br.readLine()) != null)
1490 {
1491 bw.write(s + '\n');
1492 bw.flush();
1493 }
1494 }
1495 catch (Exception e)
1496 {
1497 e.printStackTrace();
1498 }
1499 }
1500}
1501
1502Output:
1503
1504
1505
1506
1507
1508Practical 5:
1509Aim: Write a program to send an encrypted email
1510
1511Steps:
1512
1513Enable POP/IMAP
1514
1515
1516
1517Access to less secure app: Turn ON
1518https://www.google.com/settings/security/lesssecureapps
1519
1520
1521
1522
1523https://accounts.google.com/DisplayUnlockCaptcha
1524
1525
1526
1527
1528Code:
1529
1530EncryptedEMail.java
1531
1532import java.util.Properties;
1533import javax.crypto.Cipher;
1534import javax.crypto.KeyGenerator;
1535import javax.crypto.SecretKey;
1536import javax.mail.Message;
1537import javax.mail.PasswordAuthentication;
1538import javax.mail.Session;
1539import javax.mail.Transport;
1540import javax.mail.internet.InternetAddress;
1541import javax.mail.internet.MimeMessage;
1542import sun.misc.BASE64Encoder;
1543
1544public class EncryptedEMail
1545{
1546 public static void main(String[] args)
1547 {
1548 Properties props = new Properties();
1549 props.put("mail.smtp.starttls.enable", "true");
1550 props.put("mail.smtp.host", "smtp.gmail.com");
1551 props.put("mail.smtp.socketFactory.port", "587");
1552 props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
1553 props.put("mail.smtp.auth", "true");
1554 props.put("mail.smtp.port", "587");
1555
1556 Session session = Session.getDefaultInstance(props,
1557 new javax.mail.Authenticator()
1558 {
1559 protected PasswordAuthentication getPasswordAuthentication()
1560 {
1561 return new PasswordAuthentication("dnaik7418@gmail.com","D7418NAIK");
1562 }
1563 }
1564 );
1565
1566 try
1567 {
1568 String msg = "Hello all..",cipherText,decryptedText;
1569 KeyGenerator keyGen = KeyGenerator.getInstance("AES");
1570 keyGen.init(128);
1571 SecretKey secretKey = keyGen.generateKey();
1572 Cipher aesCipher = Cipher.getInstance("AES");
1573 aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
1574 byte[] byteDataToEncrypt = msg.getBytes();
1575 byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
1576 cipherText = new BASE64Encoder().encode(byteCipherText);
1577 Message message = new MimeMessage(session);
1578 message.setFrom(new InternetAddress("dnaik7418@gmail.com"));
1579 message.setRecipients(Message.RecipientType.TO,
1580 InternetAddress.parse("dnaik7418@yahoo.com"));
1581 message.setSubject("Testing Mail....");
1582 message.setText(cipherText);
1583 Transport.send(message);
1584 System.out.println("Your mail has been sent!!!");
1585 }
1586 catch (Exception e)
1587 {
1588 System.out.println(e);
1589 }
1590 }
1591}
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605Output:
1606
1607
1608
1609
1610
1611Practical 6:
1612Aim: Write a program to digitally sign MIME to create an ‘opaque’ signature.
1613
1614Code:
1615
1616GenerateKey.java
1617
1618package generateKey;
1619import java.io.*;
1620import java.security.*;
1621import java.util.logging.Level;
1622import java.util.logging.Logger;
1623
1624public class GenerateKey
1625{
1626 public static void main(String[] args)
1627 {
1628 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
1629 System.out.println("Enter the file name:");
1630 try
1631 {
1632 String f_name = br.readLine();
1633 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
1634 SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
1635 keyGen.initialize(1024, random);
1636 KeyPair pair = keyGen.genKeyPair();
1637 PrivateKey priv = pair.getPrivate();
1638 PublicKey pub = pair.getPublic();
1639 Signature dsa = Signature.getInstance("SHA1withDSA");
1640 dsa.initSign(priv);
1641 FileInputStream fis = new FileInputStream ("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 6\\"+ f_name);
1642 BufferedInputStream bufin = new BufferedInputStream(fis);
1643 byte [] buffer = new byte[1024];
1644 int len;
1645 while(bufin.available()!= 0)
1646 {
1647 len = bufin.read(buffer);
1648 dsa.update(buffer, 0, len);
1649 }
1650 bufin.close();
1651 byte [] realSig = dsa.sign();
1652 FileOutputStream sigfos = new FileOutputStream("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 6\\sig");
1653 sigfos.write(realSig);
1654 sigfos.close();
1655 byte [] key = pub.getEncoded();
1656 FileOutputStream keyfos = new FileOutputStream("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 6\\pub");
1657 keyfos.write(key);
1658 keyfos.close();
1659 }
1660 catch (Exception ex)
1661 {
1662 Logger.getLogger(GenerateKey.class.getName()).log(Level.SEVERE, null, ex);
1663 }
1664 }
1665}
1666
1667VerifyKey.java
1668
1669package verifyKey;
1670import java.io.*;
1671import java.security.*;
1672import java.security.spec.X509EncodedKeySpec;
1673import java.util.logging.Level;
1674import java.util.logging.Logger;
1675
1676public class VerifyKey
1677{
1678 public static void main(String[] args)
1679 {
1680 try
1681 {
1682 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
1683 System.out.println("Enter the public key filename:");
1684 String pub = br.readLine();
1685 System.out.println("Enter the Signature file:");
1686 String sigfile = br.readLine();
1687 System.out.println("Enter the filename:");
1688 String f_name = br.readLine();
1689 FileInputStream keyfis = new FileInputStream("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 6\\"+pub);
1690 byte [] encKey = new byte[keyfis.available()];
1691 keyfis.read(encKey);
1692 keyfis.close();
1693 X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
1694 KeyFactory keyfactory = KeyFactory.getInstance("DSA");
1695 PublicKey pubKey = keyfactory.generatePublic(pubKeySpec);
1696 FileInputStream sigfis =new FileInputStream("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 6\\"+sigfile);
1697 byte [] sigToVerify = new byte[sigfis.available()];
1698 sigfis.read(sigToVerify);
1699 sigfis.close();
1700 Signature sig = Signature.getInstance("SHA1withDSA");
1701 sig.initVerify(pubKey);
1702 FileInputStream datafis = new FileInputStream("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 6\\"+f_name);
1703 BufferedInputStream bufin = new BufferedInputStream(datafis);
1704 byte [] buffer = new byte[1024];
1705 int len;
1706 while(bufin.available()!=0)
1707 {
1708 len = bufin.read(buffer);
1709 sig.update(buffer,0,len);
1710 }
1711 bufin.close();
1712 boolean verfies = sig.verify(sigToVerify);
1713 System.out.println("Signature verfies: "+verfies);
1714 }
1715 catch (Exception ex)
1716 {
1717 Logger.getLogger(VerifyKey.class.getName()).log(Level.SEVERE, null, ex);
1718 }
1719 }
1720}
1721Output:
1722
1723
1724
1725Generating Key:
1726
1727
1728
1729
1730
1731Verifying Key:
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752Verifying Key After changing image properties:
1753
1754
1755Practical 7:
1756Aim: Write a program to generate DSA SSH Key
1757
1758Code:
1759
1760Export.java
1761
1762package export;
1763import java.security.*;
1764import java.security.spec.*;
1765import java.io.*;
1766
1767public class Export
1768{
1769 public static void main(String args[])
1770 {
1771 try
1772 {
1773 KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
1774 SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG", "SUN");
1775 kpg.initialize(1024,rnd);
1776 KeyPair kp = kpg.generateKeyPair();
1777 Class spec = Class.forName("java.security.spec.DSAPrivateKeySpec");
1778 KeyFactory kf = KeyFactory.getInstance("DSA");
1779 DSAPrivateKeySpec ks = (DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(),spec);
1780 FileOutputStream fos = new FileOutputStream("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 7\\ExportedKey.txt");
1781 ObjectOutputStream oos = new ObjectOutputStream(fos);
1782 oos.writeObject(ks.getX());
1783 oos.writeObject(ks.getP());
1784 oos.writeObject(ks.getQ());
1785 oos.writeObject(ks.getG());
1786 System.out.println("Private Key Exported");
1787 }
1788 catch(Exception e)
1789 {
1790 e.printStackTrace();
1791 }
1792 }
1793}
1794
1795Import.java
1796
1797package pkgImport;
1798import java.security.*;
1799import java.security.spec.*;
1800import java.io.*;
1801import java.math.*;
1802
1803public class Import
1804{
1805 public static void main(String args[])
1806 {
1807 try
1808 {
1809 FileInputStream fis = new FileInputStream("C:\\Users\\Darpan\\Documents\\Master in Computer Science\\Semester 2\\Practicals\\Paper 3 Cyber Security\\Practical 7\\ExportedKey.txt");
1810 ObjectInputStream ois = new ObjectInputStream(fis);
1811 DSAPrivateKeySpec ks = new DSAPrivateKeySpec((BigInteger)ois.readObject(),(BigInteger)ois.readObject(),(BigInteger)ois.readObject(), (BigInteger)ois.readObject());
1812 KeyFactory kf = KeyFactory.getInstance("DSA");
1813 PrivateKey pk = kf.generatePrivate(ks);
1814 System.out.println("Got private Key");
1815 }
1816 catch(FileNotFoundException e)
1817 {
1818 System.out.println("Key not found");
1819 }
1820 catch(Exception e1)
1821 {
1822 System.out.println("Key is corrupted");
1823 }
1824 }
1825}
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845Output: