Professional Documents
Culture Documents
Ns Practical Ready
Ns Practical Ready
Ns Practical Ready
DEGREE COLLEGE OF
SCIENCE & COMMERCE.
T.Y.B.Sc C.S.
Information &
Network Security
SHRI G.P.M. DEGREE COLLEGE OF
SCIENCE & COMMERCE.
(COMMITTED TO EXCELLENCE IN EDUCATION)
prescribed by the University of Mumbai under my supervision during the academic year 2018-
2019.
/ / ……………… ………………
Example-2: Write a program to implement Blowfish
algorithm to Perform encryption / decryption of
a string (HOMEWORK)
Practical : 1
Source code:
import java.util.*;
import java.io.*;
public class CaesarCipher{
public static void main(String arg[]) throws IOException {
char[] ch=new char[26];
ch[0]='a';ch[1]='b';ch[2]='c';ch[3]='d';ch[4]='e';
ch[5]='f';ch[6]='g';ch[7]='h';ch[8]='i';ch[9]='j';
ch[10]='k';ch[11]='l';ch[12]='m';ch[13]='n';ch[14]='o';
ch[15]='p';ch[16]='q';ch[17]='r';ch[18]='s';ch[19]='t';
ch[20]='u';ch[21]='v';ch[22]='w';ch[23]='x';ch[24]='y';
ch[25]='z';
char[] CH=new char[26];
CH[0]='A';CH[1]='B';CH[2]='C';CH[3]='D';CH[4]='E';
CH[5]='F';CH[6]='G';CH[7]='H';CH[8]='I';CH[9]='J';
CH[10]='K';CH[11]='L';CH[12]='M';CH[13]='N';CH[14]='O';
CH[15]='P';CH[16]='Q';CH[17]='R';CH[18]='S';CH[19]='T';
Page No-1/98
CH[20]='U';CH[21]='V';CH[22]='W';CH[23]='X';CH[24]='Y';
CH[25]='Z';
Scanner sc=new Scanner(System.in);
System.out.println("Enter the coice ('1' for encrypt / '2' for decrypt) : ");
int choice=sc.nextInt();
if(choice==1){
StringBuilder CipherText=new StringBuilder();
CipherText.append("");
DataInputStream dd=new DataInputStream(System.in);
System.out.println("Enter the Plain Text : ");
String PlainText=dd.readLine();
System.out.println("\nPlaint Text : "+PlainText);
// Code for algorithm to encrypt
for(int i=0;i<PlainText.length();i++){
char pt=PlainText.charAt(i);
if(pt>='a' && pt<='z' || pt>='A' && pt<='Z'){
if(Character.isUpperCase(pt)){
int pos=new String(CH).indexOf(pt);
pos+=3;
if(pos>25)
pos=pos%26;
CipherText.append(CH[pos]);
}
else {
int pos=new String(ch).indexOf(pt);
pos+=3;
if(pos>25)
pos=pos%26;
CipherText.append(ch[pos]);
}
}
else
CipherText.append(pt);
}
System.out.println("\nCipher Text : "+CipherText);
}
else if(choice==2){
StringBuilder PlainText=new StringBuilder();
PlainText.append("");
Page No-2/98
System.out.println("Enter the Cipher Text : ");
DataInputStream dd=new DataInputStream(System.in);
String CipherText=dd.readLine();
System.out.println("\nCipher Text : "+CipherText);
// Code for algorithm to decrypt
for(int i=0;i<CipherText.length();i++){
char ct=CipherText.charAt(i);
if(ct>='a' && ct<='z' || ct>='A' && ct<='Z'){
if(Character.isUpperCase(ct)){
int pos=new String(CH).indexOf(ct);
pos-=3;
if(pos<0){
pos=pos*(-1);
pos=26-pos;
}
PlainText.append(CH[pos]);
}
else {
int pos=new String(ch).indexOf(ct);
pos-=3;
if(pos<0){
pos=pos*(-1);
pos=26-pos;
}
PlainText.append(ch[pos]);
}
}
else
PlainText.append(ct);
}
System.out.println("\nPlain Text : "+PlainText);
}
else
System.out.println("Sorry! you have entered wrong choice...");
}
}
Page No-3/98
Output-
Page No-4/98
Practical 1: Example 1:
Source code:
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Scanner;
public class MonoalphabeticCipher {
public static void main(String arg[]) throws IOException {
char[] ch=new char['z'+1];
ch['a']='z';ch['b']='y';ch['c']='x';ch['d']='w';ch['e']='v';
ch['f']='u';ch['g']='t';ch['h']='s';ch['i']='r';ch['j']='q';
ch['k']='p';ch['l']='o';ch['m']='n';ch['n']='m';ch['o']='l';
ch['p']='k';ch['q']='j';ch['r']='i';ch['s']='h';ch['t']='g';
ch['u']='f';ch['v']='e';ch['w']='d';ch['x']='c';ch['y']='b';
ch['z']='a';
char[] CH=new char['Z'+1];
CH['A']='Z';CH['B']='Y';CH['C']='X';CH['D']='W';CH['E']='V';
CH['F']='U';CH['G']='T';CH['H']='S';CH['I']='R';CH['J']='Q';
CH['K']='P';CH['L']='O';CH['M']='N';CH['N']='M';CH['O']='L';
CH['P']='K';CH['Q']='J';CH['R']='I';CH['S']='H';CH['T']='G';
CH['U']='F';CH['V']='E';CH['W']='D';CH['X']='C';CH['Y']='B';
CH['Z']='A';
Scanner sc=new Scanner(System.in);
System.out.println("Enter the coice ('1' for encrypt / '2' for decrypt) : ");
int choice=sc.nextInt();
switch (choice) {
case 1:
{
StringBuilder CipherText=new StringBuilder();
CipherText.append("");
DataInputStream dd=new DataInputStream(System.in);
System.out.println("Enter the Plain Text : ");
String PlainText=dd.readLine();
System.out.println("\nPlaint Text : "+PlainText);
// Code for algorithm to encrypt
for(int i=0;i<PlainText.length();i++){
Page No-5/98
char pt=PlainText.charAt(i);
if(pt>='a' && pt<='z' || pt>='A' && pt<='Z'){
if(Character.isUpperCase(pt)){
char pos=(char) new String(CH).indexOf(pt);
CipherText.append(pos);
}
else {
char pos=(char) new String(ch).indexOf(pt);
CipherText.append(pos);
}
}
else
CipherText.append(pt);
}
System.out.println("\nCipher Text : "+CipherText);
break;
}
case 2:
{
StringBuilder PlainText=new StringBuilder();
PlainText.append("");
System.out.println("Enter the Cipher Text : ");
DataInputStream dd=new DataInputStream(System.in);
String CipherText=dd.readLine();
System.out.println("\nCipher Text : "+CipherText);
// Code for algorithm to decrypt
for(int i=0;i<CipherText.length();i++){
char ct=CipherText.charAt(i);
if(ct>='a' && ct<='z' || ct>='A' && ct<='Z'){
if(Character.isUpperCase(ct))
PlainText.append(CH[ct]);
else
PlainText.append(ch[ct]);
}
else
PlainText.append(ct);
}
System.out.println("\nPlain Text : "+PlainText);
break;
Page No-6/98
}
default:{
System.out.println("Sorry! you have entered wrong choice...");
break;
}
}
}
}
Output:
Page No-7/98
Practical 1: Example 2:
Source code:
importjavax.swing.JOptionPane;
public class ModifiedCaesar_Cipher {
public static void main(String[] args)
{
String plain_text;
String key;
String cipher1,cipher2;
plain_text=JOptionPane.showInputDialog("Input the string to encrypt:");
key=JOptionPane.showInputDialog("Input the key:");
cipher1=encrypt(plain_text,key);
JOptionPane.showMessageDialog (null, "Cipher Text is " + cipher1, "Encryption
Process", JOptionPane.PLAIN_MESSAGE);
cipher2=decrypt(cipher1,key);
JOptionPane.showMessageDialog (null, "Plain Text is " + cipher2, "Decryption Process",
JOptionPane.PLAIN_MESSAGE);
}
public static String encrypt(String str1,String key1)
{
intkeylen=Integer.parseInt(key1);
String encrypted="";
for(int i=0;i<str1.length();i++)
{
int c=str1.charAt(i);
if(Character.isUpperCase(c))
{
c=c+(keylen%26);
if(c>'Z')
c=c-26;
}
else if(Character.isLowerCase(c))
{
c=c+(keylen%26);
if(c>'z')
c=c-26;
}
encrypted+=(char)c;
keylen++;
}
return encrypted;
Page No-8/98
}
public static String decrypt(String str1,String key1)
{
intkeylen=Integer.parseInt(key1);
String decrypted="";
for(int i=0;i<str1.length();i++)
{
int c=str1.charAt(i);
if(Character.isUpperCase(c))
{
c=c-(keylen%26);
if(c<'A')
c=c+26;
}
else if(Character.isLowerCase(c))
{
c=c-(keylen%26);
if(c<'a')
c=c+26;
}
decrypted+=(char)c;
keylen++;
}
return decrypted;
}
}
Output:
Page No-9/98
Theory -2
Theory:
As introduction to stream ciphers, and to demonstrate that a perfect cipher does exist, we
describe the Vernam Cipher, also known as the one-time-pad.
Gilbert Vernam invented and patented his cipher in 1917 while working at AT&T. The teletype
had been recently introduced, and along with this the commerical Baudot code. Now messages
were uniformly thought of as streams of zero's and one's Vernam proposed a bit-wise exclusive
or of the message stream with a truely random zero-one stream which was shared by sender and
receipient.
Practical : 2
Aim: Write programs to implement the following Substitution Cipher Techniques: Vernam
Cipher
Source code:
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Random;
import static jdk.nashorn.internal.objects.NativeString.toUpperCase;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author modis
*/
public class VernamCipher {
public static void main(String arg[]) throws IOException{
System.out.println("\nReference - ");
for(int i=1;i<27;i++)
System.out.print((char)(i+64)+"-"+i+" ");
DataInputStream d=new DataInputStream(System.in);
Page No-10/98
System.out.print("\n\nEnter the Plain Text : ");
String plainText=d.readLine();
plainText=toUpperCase(plainText);
String modPlainText="";
//code to remove the whitespaces
for(int k=0;k<plainText.length();k++){
char c=plainText.charAt(k);
if(c>='A'&&c<='Z'){
modPlainText+=c;
}
}
//Generate Random one-time pad
String oneTimePad="";
String cipher="";
for(int k=0;k<modPlainText.length();k++){
Random rand=new Random();
int randNum=rand.nextInt(26)+1;
oneTimePad+=(char)(randNum+64);
}
System.out.println("\n||\tPlain\t||\tOne-Time\t||\tInitial\t\t||\tMod 27\t\t||\tCipher\t||");
System.out.println("||\tText\t||\tPad\t\t||\tTotal\t\t||\t(if>26)\t\t||\tText\t||");
System.out.println("------------------------------------------------------------------------------------------
----------------");
for(int k=0;k<modPlainText.length();k++){
int a=(int)(modPlainText.charAt(k)-64);
int b=(int)(oneTimePad.charAt(k)-64);
if((a+b)>26)
{
System.out.println("||\t"+(char)(a+64)+" ("+a+")\t||\t"+(char)(b+64)+"
("+b+")\t\t||\t"+(a+b)+"\t\t||\t"+((a+b)-26)+"\t\t||\t"+(char)(((a+b)-26)+64)+"\t||");
cipher+=(char)(((a+b)-26)+64);
}
else{
System.out.println("||\t"+(char)(a+64)+" ("+a+")\t||\t"+(char)(b+64)+"
("+b+")\t\t||\t"+(a+b)+"\t\t||\t"+(a+b)+"\t\t||\t"+(char)((a+b)+64)+"\t||");
cipher+=(char)(((a+b)-26)+64);
}
}
System.out.println("\nCipher Text : "+cipher);
Page No-11/98
}
}
Output:
Page No-12/98
Practical 2: Example 1:
Aim: Write programs to implement the following Substitution Cipher Techniques: Playfair
Cipher
Source code:
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.Character.toUpperCase;
/*
* @author Pankaj Yadav
*/
public class PlayFairCipher {
public static void main(String arg[]) throws IOException{
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter the keyword : ");
String keyword=d.readLine();
//Matrix formation
char[][] matrix=new char[5][5];
boolean keydone=false;
int i=0,j=0;
boolean filled=false;
for(int k=0;k<keyword.length()&&keydone!=true;k++){
filled=false;
char c=keyword.charAt(k);
c=toUpperCase(c);
if(c>='A'&&c<='Z'){
//checking taht character is already inserted in matrix or not
for(int m=0;m<5;m++){
for(int n=0;n<5;n++){
if(matrix[m][n]==c)
filled=true;
}
}
if(!filled){
matrix[i][j]=c;
j++;
if(j==5){
i++;
j=0;
}
}
}
if(k==keyword.length()-1)
keydone=true;
}
Page No-13/98
for(char k='A';k<='Z';k++){
filled=false;
for(int m=0;m<5;m++){
for(int n=0;n<5;n++){
if(matrix[m][n]==k)
filled=true;
}
}
if(!filled){
if(k=='J')
continue;
matrix[i][j]=k;
j++;
if(j==5){
i++;
j=0;
}
}
}
System.out.print("\nTransformation Table\n");
for(i=0;i<5;i++){
for(j=0;j<5;j++){
System.out.print(" "+matrix[i][j]);
}
System.out.print("\n");
}
//Dividing whloe string in two-two character blocks
System.out.println("\nEnter the Plain Text : ");
String plainText=d.readLine();
plainText=plainText.toUpperCase();
String modPlainText="";
int l=0;
char lastChar='.';
for(int k=0;k<plainText.length();k++){
if(l==2)
l=0;
char c=plainText.charAt(k);
if(c>='A'&&c<='Z'){
if(lastChar==c&&l==1){
modPlainText+='X';
lastChar='X';
k--;
}
else{
modPlainText+=c;
lastChar=c;
Page No-14/98
}
l++;
if(l==2)
modPlainText+=" ";
}
}
if(l==1)
modPlainText+='X';
System.out.println("\nPlain Text : "+modPlainText);
// Encryption process starts here
l=0;
String cipherText="";
int x1=0,y1=0,x2=0,y2=0;
//label to come directly here from inner loops
//label always should be just above the loop
outer:
for(int k=0;k<modPlainText.length();k++){
if(l==2)
l=0;
char c=modPlainText.charAt(k);
if(c=='J')
c='I';
if(c>='A'&&c<='Z'){
for(int m=0;m<5;m++){
for(int n=0;n<5;n++){
if(c==matrix[m][n]){
if(l==0){
x1=m;y1=n;
l++;
continue outer;
}
if(l==1)
{
x2=m;y2=n;
// Replacing plain text with cipher text
if(x1==x2){
y1++; y2++;
if(y1==5)
y1=0;
if(y2==5)
y2=0;
cipherText+=matrix[x1][y1];
cipherText+=matrix[x2][y2];
}
else if(y1==y2){
x1++; x2++;
Page No-15/98
if(x1==5)
x1=0;
if(x2==5)
x2=0;
cipherText+=matrix[x1][y1];
cipherText+=matrix[x2][y2];
}
else{
cipherText+=matrix[x1][y2];
cipherText+=matrix[x2][y1];
}
l++;
continue outer;}}}}}
else
cipherText+=c;
}
System.out.println("\nCipher Text : "+cipherText+"\n");
}
}
Output:
Page No-16/98
Practical 2: Example 2:
Aim: Write programs to implement the following Substitution Cipher Techniques: Poly
alphabetic Cipher
Source code:
package polyciipher;
import java.util.*;
/**
*
* @author ZISSAN
*/
public class PolyCiipher {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int[] j = new int[100];
int[] s = new int[100];
String test="";
// initialization of the Scanner class,handles input from user,can be found in the
java.util.*; library.
// we are creating object "in" from the scanner and telling java that this will be System
input
try{
Scanner in = new Scanner(System.in);
System.out.println("Enter the plain text(STRING SHOULD BE IN UPPERCASE
AND DONT GIVE SPACE BETWEEN WORDS)::");
// next() is a method which gets the next string of text that a user types on the
keyboard
test = in.nextLine();
for ( int i = 0; i < test.length(); ++i ) {
char c = test.charAt( i );// "c" holds the individual character of the string
s[i] = (int) c-65;
}
for(int i=0;i<test.length()-1;i++){
Page No-17/98
j[i+1]=s[i];
}
System.out.println("Enter the key::");
int k = Integer.parseInt(in.nextLine());
j[0]=k;
System.out.println();
System.out.println("The position of the character in the cipher text::");
for(int i=0;i<test.length();i++){
j[i]=j[i]+s[i];
j[i]=j[i]%26;
System.out.print(j[i]);
}
System.out.println();
System.out.println("The cipher text::");
for(int i=0;i<test.length();i++){
char c=(char) (j[i]+65);
System.out.print(c);
}
System.out.println();
}
catch(Exception er){
System.out.println("--YOU HAVE TYPE INVALID DATA--");
}
}
}
Output:
Although weak on its own, it can be combined with other ciphers, such as a substitution cipher,
the combination of which can be more difficult to break than either cipher on it's own.
the ADFGVX cipheruses a columnar transposition to greatly improve its security
Practical : 3
Aim: Write a Program to implement the following substitution cipher techniques: Rail
fence cipher
Source code:
port java.io.DataInputStream;
import java.io.IOException;
public class RailFenceCipher {
public static void main(String arg[])throws IOException{
DataInputStream d=new DataInputStream(System.in);
System.out.print("\nEnter the plain text : ");
String plainText=d.readLine();
//Encryption
String cipherText="";
for(int i=0;i<plainText.length();i+=2)
cipherText+=plainText.charAt(i);
for(int i=1;i<plainText.length();i+=2)
cipherText+=plainText.charAt(i);
System.out.println("\nCipher Text : "+cipherText);
//Decryption
plainText="";
int len=cipherText.length();
if(len%2==0){
for(int i=0;i<(len/2);i++){
plainText+=cipherText.charAt(i);
plainText+=cipherText.charAt(i+(len/2));
Page No-19/98
}
}
else{
for(int i=0;i<(len/2)+1;i++){
plainText+=cipherText.charAt(i);
if(i!=(len/2))
plainText+=cipherText.charAt(i+(len/2)+1);
}
}
System.out.println("\nPlain Text : "+plainText+"\n");
}
}
Output:
Page No-20/98
Practical 3: Example 1:
Aim: Write a Program to implement the following substitution cipher techniques: Simple
Columnar Technique
Source code:
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class SimpleColumnarCipher {
//code for sorting of string
public static String sortString(String inputString){
char tempArray[]=inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
public static void main(String arg[]) throws IOException{
DataInputStream d=new DataInputStream(System.in);
String plaintext="",key,ciphertext="";
int pos=0;
System.out.print("\nEnter 1 for Encryption and 2 for Decryption : ");
int choice=Integer.parseInt(d.readLine());
if(choice==1){
System.out.print("\nEnter the Plaintext : ");
plaintext=d.readLine();
System.out.print("\nEnter the key : ");
key=d.readLine();
int y=key.length();
int strlen=plaintext.length();
int x=(strlen/y)+1;
char[][] matrix=new char[x][y];
String sorted=sortString(key);
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
if(pos<strlen){
matrix[i][j]=plaintext.charAt(pos);
pos++;
System.out.print(matrix[i][j]+"\t");
}
else
matrix[i][j]=' ';
}
System.out.println("\n");
Page No-21/98
}
for(int j=0;j<y;j++){
int k=key.indexOf(sorted.charAt(j));
for(int i=0;i<x;i++){
ciphertext+=matrix[i][k];
}
}
System.out.print("Ciphertext : "+ciphertext);
}
if(choice==2){
System.out.print("\nEnter the Ciphertext : ");
ciphertext=d.readLine();
System.out.print("\nEnter the key : ");
key=d.readLine();
int y=key.length();
int strlen=ciphertext.length();
int x=(strlen/y)+1;
char[][] matrix=new char[x][y];
String sorted=sortString(key);
for(int j=0;j<y;j++){
int k=key.indexOf(sorted.charAt(j));
for(int i=0;i<x;i++){
if(pos<strlen){
matrix[i][k]=ciphertext.charAt(pos);
pos++;
}
else
matrix[i][k]=' ';
}
}
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
plaintext+=matrix[i][j];
}
}
System.out.println("\nPlaintext : "+plaintext);
}
}
}
Page No-22/98
Output:
Page No-23/98
Practical 3: Example 2:
Aim: Write a Program to implement the following substitution cipher techniques: Multi
Columnar Technique
Source code:
import java.util.*;
import java.io.*;
import java.lang.*;
System.out.print("Enter Key:");
String key = scan.next();
System.out.println(encryptCT(key, text).toUpperCase());
break;
case 2:
System.out.print("Enter Encrypted String:");
text = scan.next();
System.out.print("Enter Key:");
key = scan.next();
System.out.println(decryptCT(key, text));
break;
default:
break;
}
}
Page No-24/98
int[] arrange = arrangeKey(key);
z++;
}
}
String enc = "";
for (int x = 0; x < lenkey; x++) {
for (int y = 0; y < lenkey; y++) {
if (x == arrange[y]) {
for (int a = 0; a < row; a++) {
enc = enc + grid[a][y];
}
}
}
}
return enc;
}
Page No-25/98
for (int x = 0; x < lenkey; x++) {
for (int y = 0; y < lenkey; y++) {
if (arrange[x] == y) {
for (int z = 0; z < row; z++) {
grid[z][y] = get[arrange[y]].charAt(z);
}
}
}
}
return dec;
}
return num;
}
}
Page No-26/98
Output:
Page No-27/98
Theory -4
Theory:
For each text in the message there is a corresponding text in the key. So the secret key is equal or
more in length than the message to be communicated. We map the alphabets to number as A->1,
B->2 etc. Each character from the message and its corresponding character in key is added
converted to modulo 26. Then the resulting number is mapped back to a character. For
decryption, reverse of the same technique is used. Why modulo 26 as it restricts the character set
from A to Z.
Practical : 4
Source code:
package com.javapapers.java.security;
Page No-28/98
}
return encryptedString.toString();
}
Output:
Page No-29/98
Practical 4: Example 1:
Aim: Write a Program to encrypt and decrypt the strings using AES Algorithm
Source code:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
import java.util.*;
public class RSA
{
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private Random r;
public RSA()
{
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
{
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger N)
{
this.e = e;
this.d = d;
this.N = N;
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);
String teststring;
Page No-30/98
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: "
+ bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
System.out.println("Encrypted String : "+encrypted);
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
{
String test = "";
for (byte b : encrypted)
{
test+=Byte.toString(b);
}
return test;
}
// Encrypt message
public byte[] encrypt(byte[] message)
{
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message)
{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}
Page No-31/98
Output:
Page No-32/98
Practical 4: Example 2:
Aim: Write a Program to encrypt and decrypt the strings using DES Algorithm
Source code:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import com.sun.mail.util.BASE64DecoderStream;
import com.sun.mail.util.BASE64EncoderStream;
import java.util.Scanner;
public class DES {
private static Cipher ecipher;
private static Cipher dcipher;
private static SecretKey key;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
try {
// generate secret key using DES algorithm
key = KeyGenerator.getInstance("DES").generateKey();
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
// initialize the ciphers with the given key
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
System.out.print("Enter Plain Text : ");
String plainText=sc.nextLine();
String encrypted = encrypt(plainText);
System.out.println("Encrypted Text : " + encrypted);
String decrypted = decrypt(encrypted);
System.out.println("Decrypted Text : " + decrypted);
}
catch (NoSuchAlgorithmException e) {
System.out.println("No Such Algorithm:" + e.getMessage());
return;
}
catch (NoSuchPaddingException e) {
System.out.println("No Such Padding:" + e.getMessage());
return;
}
catch (InvalidKeyException e) {
Page No-33/98
System.out.println("Invalid Key:" + e.getMessage());
return;
}
}
public static String encrypt(String str) {
try {
// encode the string into a sequence of bytes using the named charset
// storing the result into a new byte array.
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
// encode to base64
enc = BASE64EncoderStream.encode(enc);
return new String(enc);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String str) {
try {
// decode with base64 to get bytes
byte[] dec = BASE64DecoderStream.decode(str.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
// create new string based on the specified charset
return new String(utf8, "UTF8");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
Page No-34/98
Output:
Page No-35/98
Theory -5
Theory:
Encryption is the process of translating plain text data (plaintext) into something that appears to
be random and meaningless (ciphertext). Decryption is the process of converting ciphertext
back to plaintext.
To encrypt more than a small amount of data, symmetric encryption is used. A symmetric key is
used during both the encryption and decryption processes. To decrypt a particular piece of
ciphertext, the key that was used to encrypt the data must be used.
The goal of every encryption algorithm is to make it as difficult as possible to decrypt the
generated ciphertext without using the key. If a really good encryption algorithm is used, there is
no technique significantly better than methodically trying every possible key. For such an
algorithm, the longer the key, the more difficult it is to decrypt a piece of ciphertext without
possessing the key.
Practical : 5
Source code:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
import java.util.*;
public class RSA
{
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private Random r;
public RSA()
{
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
Page No-36/98
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
{
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger N)
{
this.e = e;
this.d = d;
this.N = N;
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: "
+ bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
System.out.println("Encrypted String : "+encrypted);
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
{
String test = "";
for (byte b : encrypted)
{
test+=Byte.toString(b);
}
return test;
}
// Encrypt message
public byte[] encrypt(byte[] message)
Page No-37/98
{
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message)
{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}
Output:
Page No-38/98
Practical 5: Example 1:
Source code:
import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
System.out.println("Encrypting...");
byte[] encrypted = encrypt(toEncrypt, "password");
System.out.println("Decrypting...");
String decrypted = decrypt(encrypted, "password");
// enctypt!
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
Page No-39/98
return encrypted;
}
Page No-40/98
Conclusion: The Program Successfully run and compiled
Page No-41/98
Practical 5: Example 2:
Source code:
import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random ;
class Blowfish {
byte[] skey = new byte[1000];
String skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage;
public Blowfish() {
try {
generateSymmetricKey();
inputMessage=JOptionPane.showInputDialog(null,"Enter message to encrypt");
byte[] ibyte = inputMessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\n"+encryptedData);
byte[] dbyte= decrypt(raw,ebyte);
String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);
JOptionPane.showMessageDialog(null,"Decrypted Data "+"\n"+decryptedMessage);
}
catch(Exception e) {
System.out.println(e);
}
}
void generateSymmetricKey() {
try {
Random r = new Random();
int num = r.nextInt(10000);
String knum = String.valueOf(num);
byte[] knumb = knum.getBytes();
Page No-42/98
skey=getRawKey(knumb);
skeyString = new String(skey);
System.out.println("Blowfish Symmetric key = "+skeyString);
}
catch(Exception e) {
System.out.println(e);
}
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 128, 256 and 448 bits may not be available
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[]) {
Blowfish bf = new Blowfish();
}
}
Page No-43/98
Output:
Page No-44/98
Theory -6
Theory:
Asymmetric Encryption of data requires transfer of cryptographic private key. The most
challenging part in this type of encryption is the transfer of the encryption key from sender to
receiver without anyone intercepting this key in between. This transfer or rather generation on
same cryptographic keys at both sides secretively was made possible by the Diffie-Hellman
algorithm.
The Diffie-Hellman algorithm was developed by Whitfield Diffie and Martin Hellman in 1976.
This algorithm was devices not to encrypt the data but to generate same private cryptographic
key at both ends so that there is no need to transfer this key from one communication end to
another. Though this algorithm is a bit slow but it is the sheer power of this algorithm that makes
it so popular in encryption key generation.
Practical : 6
Aim: Write a program to implement the Diffie- Hellman Key Agreement algorithm to
Generate symmetric keys
Source code:
import java.io.DataInputStream;
import java.io.IOException;
public class DeffiehellMan {
public static void main(String arg[])throws IOException{
DataInputStream d=new DataInputStream(System.in);
System.out.print("\nEnter the secret key for the Alice : ");
int x=Integer.parseInt(d.readLine());
System.out.print("Enter the secret key for the Bob : ");
int y=Integer.parseInt(d.readLine());
System.out.print("Enter the First prime number(g) : ");
int g=Integer.parseInt(d.readLine());
System.out.print("Enter the Second prime number(n) : ");
int n=Integer.parseInt(d.readLine());
int A=(int) ((Math.pow(g,x))%n);
System.out.println("A calculated by Alice : "+A);
int B=(int) ((Math.pow(g,y))%n);
System.out.println("B calculated by Bob : "+B);
int k1=(int) ((Math.pow(B,x))%n);
Page No-45/98
System.out.println("K1 calculated by Alice : "+k1);
int k2=(int) ((Math.pow(A,y))%n);
System.out.println("K2 calculated by Bob : "+k2);
if(k1==k2){
System.out.println("Shared secret key is : "+k1+"\n");
}
}
}
Output:
Page No-46/98
Practical 6: Example 1:
Aim: Write a program to implement the Diffie- Hellman Key Agreement algorithm to
Generate Asymmetric keys
Source code:
import java.util.*;
public class DeffieDemo
{
public static void main(String[] args)
{
int k1,k2,a,b,g,n,x,y;
boolean b1,b2;
Scanner s = new Scanner(System.in);
System.out.println("Enter a value for g");
g = s.nextInt();
System.out.println("Enter a value for n");
n = s.nextInt();
b1 = prime(g);
b2 = prime(n);
while(b1 == false || b2 == false)
{
System.out.println("Enter the value for g & n");
g = s.nextInt();
n = s.nextInt();
b1 = prime(g);
b2 = prime(n);
}
System.out.println("Enter a value for x");
x = s.nextInt();
a = power(g,x)%n;
System.out.println("Value of A :"+a);
System.out.println("Enter a value for y");
y = s.nextInt();
b = power(g,y)%n;
System.out.println("Value of B :"+b);
k1 = power(b,x)%n;
System.out.println("Value of k1 "+k1);
k2 = power(a,y)%n;
System.out.println("Value of k2 "+k2);
if(k1 == k2)
{
System.out.println("Connection Established...");
}
else
Page No-47/98
{
Page No-48/98
Output:
Page No-49/98
Practical 6: Example 2:
Aim: Write a program to implement the public key Cryptosystems to generate Asymmetric
keys
Source code:
package com.mkyong.asymmetric;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.codec.binary.Base64;
Page No-50/98
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
//
https://docs.oracle.com/javase/8/docs/api/java/security/spec/X509EncodedKeySpec.html
public PublicKey getPublic(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
public void encryptFile(byte[] input, File output, PrivateKey key)
throws IOException, GeneralSecurityException {
this.cipher.init(Cipher.ENCRYPT_MODE, key);
writeToFile(output, this.cipher.doFinal(input));
}
public void decryptFile(byte[] input, File output, PublicKey key)
throws IOException, GeneralSecurityException {
this.cipher.init(Cipher.DECRYPT_MODE, key);
writeToFile(output, this.cipher.doFinal(input));
}
Page No-51/98
public String decryptText(String msg, PublicKey key)
throws InvalidKeyException, UnsupportedEncodingException,
IllegalBlockSizeException, BadPaddingException {
this.cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(Base64.decodeBase64(msg)), "UTF-8");
}
if (new File("KeyPair/text.txt").exists()) {
ac.encryptFile(ac.getFileInBytes(new File("KeyPair/text.txt")),
new File("KeyPair/text_encrypted.txt"),privateKey);
ac.decryptFile(ac.getFileInBytes(new
File("KeyPair/text_encrypted.txt")),
new File("KeyPair/text_decrypted.txt"), publicKey);
} else {
System.out.println("Create a file text.txt under folder KeyPair");
}
}}
Page No-52/98
Output:
Page No-53/98
Theory -7
Theory:
MD5 is a cryptographic message digest algorithm. MD5 hash considered to be one of the most
widely-used used secure hashing functions, producing a 128-bit digest (32 hex numbers) from
any data. While Java has built-in cryptographic checksum classes, it's quite uneasy to use them
for a simple task -- calculate MD5 hash from string and return 32-byte hexadecimal
representation.
Practical : 7
Aim: Write a program to implement the MD5 algorithm compute the message digest
Source code:
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
public class MD5 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a text : ");
String i=sc.nextLine();
System.out.println(md5(i));
System.out.println("For null :" + md5(""));
System.out.println("For simple text :"+ md5("This is my text"));
System.out.println("For simple numbers : " + md5("12345"));
}
public static String md5(String input) {
String Md5 = null;
if(null == input)
return null;
try {
//Create MessageDigest object for MD5
MessageDigest digest = MessageDigest.getInstance("MD5");
//Update input string in message digest
digest.update(input.getBytes(), 0, input.length());
//Converts message digest value in base 16 (hex)
Md5 = new BigInteger(1, digest.digest()).toString(16);
}
catch (NoSuchAlgorithmException e) {
Page No-54/98
e.printStackTrace();
}
return Md5;
}
}
Output:
Page No-55/98
Practical 7: Example 1:
Aim: Write a program to implement the MD4 algorithm compute the message digest
Source code:
import java.security.MessageDigest;
/**
* Implements the MD4 message digest algorithm in Java.
* <p>
* <b>References:</b>
* <ol>
* <li> Ronald L. Rivest,
* "<a href="http://www.roxen.com/rfc/rfc1320.html">
* The MD4 Message-Digest Algorithm</a>",
* IETF RFC-1320 (informational).
* </ol>
*
* <p><b>$Revision: 1.2 $</b>
* @author Raif S. Naffah
*/
public class MD4 extends MessageDigest implements Cloneable
{
// MD4 specific object variables
//...........................................................................
/**
* The size in bytes of the input block to the tranformation algorithm.
*/
private static final int BLOCK_LENGTH = 64; // = 512 / 8;
/**
* 4 32-bit words (interim result)
*/
private int[] context = new int[4];
/**
* Number of bytes processed so far mod. 2 power of 64.
*/
private long count;
Page No-56/98
/**
* 512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits.
*/
private byte[] buffer = new byte[BLOCK_LENGTH];
/**
* 512 bits work buffer = 16 x 32-bit words
*/
private int[] X = new int[16];
// Constructors
//...........................................................................
public MD4 () {
super("MD4");
engineReset();
}
/**
* This constructor is here to implement cloneability of this class.
*/
private MD4 (MD4 md) {
this();
context = (int[])md.context.clone();
buffer = (byte[])md.buffer.clone();
count = md.count;
}
/**
* Returns a copy of this MD object.
*/
public Object clone() { return new MD4(this); }
// JCE methods
Page No-57/98
//...........................................................................
/**
* Resets this object disregarding any temporary data present at the
* time of the invocation of this call.
*/
public void engineReset () {
// initial values of MD4 i.e. A, B, C, D
// as per rfc-1320; they are low-order byte first
context[0] = 0x67452301;
context[1] = 0xEFCDAB89;
context[2] = 0x98BADCFE;
context[3] = 0x10325476;
count = 0L;
for (int i = 0; i < BLOCK_LENGTH; i++)
buffer[i] = 0;
}
/**
* Continues an MD4 message digest using the input byte.
*/
public void engineUpdate (byte b) {
// compute number of bytes still unhashed; ie. present in buffer
int i = (int)(count % BLOCK_LENGTH);
count++; // update number of bytes
buffer[i] = b;
if (i == BLOCK_LENGTH - 1)
transform(buffer, 0);
}
/**
* MD4 block update operation.
* <p>
* Continues an MD4 message digest operation, by filling the buffer,
* transform(ing) data in 512-bit message block(s), updating the variables
* context and count, and leaving (buffering) the remaining bytes in buffer
* for the next update or finish.
*
* @param input input block
* @param offset start of meaningful bytes in input
Page No-58/98
* @param len count of bytes in input block to consider
*/
public void engineUpdate (byte[] input, int offset, int len) {
// make sure we don't exceed input's allocated size/length
if (offset < 0 || len < 0 || (long)offset + len > input.length)
throw new ArrayIndexOutOfBoundsException();
transform(buffer, 0);
/**
* Completes the hash computation by performing final operations such
* as padding. At the return of this engineDigest, the MD engine is
* reset.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] engineDigest () {
// pad output to 56 mod 64; as RFC1320 puts it: congruent to 448 mod 512
int bufferNdx = (int)(count % BLOCK_LENGTH);
int padLen = (bufferNdx < 56) ? (56 - bufferNdx) : (120 - bufferNdx);
Page No-59/98
byte[] tail = new byte[padLen + 8];
tail[0] = (byte)0x80;
engineUpdate(tail, 0, tail.length);
// own methods
//...........................................................................
/**
* MD4 basic transformation.
* <p>
* Transforms context based on 512 bits from input block starting
* from the offset'th byte.
*
* @param block input sub-array.
* @param offset starting position of sub-array.
*/
private void transform (byte[] block, int offset) {
Page No-60/98
X[i] = (block[offset++] & 0xFF) |
(block[offset++] & 0xFF) << 8 |
(block[offset++] & 0xFF) << 16 |
(block[offset++] & 0xFF) << 24;
int A = context[0];
int B = context[1];
int C = context[2];
int D = context[3];
Page No-61/98
A = GG(A, B, C, D, X[ 3], 3);
D = GG(D, A, B, C, X[ 7], 5);
C = GG(C, D, A, B, X[11], 9);
B = GG(B, C, D, A, X[15], 13);
context[0] += A;
context[1] += B;
context[2] += C;
context[3] += D;
}
Page No-62/98
return t << s | t >>> (32 - s);
}
}
Output:
Page No-63/98
Practical 7: Example 2:
Aim: Write a program to implement the RC5 algorithm compute the message digest
Source code:
import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
System.out.println("Encrypting...");
byte[] encrypted = encrypt(toEncrypt, "password");
System.out.println("Decrypting...");
String decrypted = decrypt(encrypted, "password");
// enctypt!
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
Page No-64/98
return encrypted;
}
Output:
Page No-65/98
Theory -8
calculate Signature
Theory:
Hash-based Message Authentication Code (HMAC) is a message authentication code that uses
a cryptographic key in conjunction with a hash function.
Hash-based message authentication code (HMAC) provides the server and the client each with
a private key that is known only to that specific server and that specific client. The client creates
a unique HMAC, or hash, per request to the server by hashing the request data with the private
keys and sending it as part of a request. What makes HMAC more secure than Message
Authentication Code (MAC) is that the key and the message are hashed in separate steps.
Practical : 8
Source code:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
Page No-66/98
for (byte b : bytes) {
formatter.format("%02x", b);
}
return formatter.toString();
}
System.out.println(hmac);
assert hmac.equals("104152c5bfdca07bc633eebd46199f0255c9f49d");
}}
Output:
Page No-67/98
Practical 8: Example 1:
Aim: Write a program to calculate HMAC-SHA0 Signature
Source code:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
return formatter.toString();
}
System.out.println(hmac);
Page No-68/98
assert hmac.equals("104152c5bfdca07bc633eebd46199f0255c9f49d");
}
Output:
Page No-69/98
Practical 8: Example 2:
Source code:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
return formatter.toString();
}
Page No-70/98
System.out.println(hmac);
assert hmac.equals("104152c5bfdca07bc633eebd46199f0255c9f49d");
}
}
Output:
Page No-71/98
Theory -9
Theory:
An SSL (Secure Sockets Layer) is the standard security protocol used to establish an encrypted
connection between a server and a client. After the establish the connection SSL/TLS ensures
that the data transmitted between server and client are secured and intact.
SSL is used by many application and banking website to make the data private and secure. It
provides the security in the transmission of sensitive data like credit/debit card number, user
login name, and password.
Practical : 9
Source code:
1. ChatServer.java
import java.net.*;
import java.io.*;
public class ChatServer
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
BufferedReader cin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
Page No-72/98
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
2. ChatClient.java
import java.net.*;
import java.io.*;
public class ChatClient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("localhost",2000);
BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE"))
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
Page No-73/98
Output:
Page No-74/98
Practical 9: Example 1:
Source code:
System.out.println(hash_Set);
// Set deonstration using TreeSet
System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
}}
Page No-75/98
Practical 9: Example 2:
Source code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
// change accordingly
String from = "akash@gmail.com";
// or IP address
String host = "localhost";
// mail id
final String username = "username@gmail.com"
System.out.println("TLSEmail Start");
// Get the session object
// SSL Port
properties.put("mail.smtp.port", "465");
Page No-76/98
// enable authentication
properties.put("mail.smtp.auth", "true");
// SSL Factory
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
"password");
}
});
}
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("subject");
message.setText("Hello, aas is sending email ");
// Send message
Page No-77/98
Transport.send(message);
System.out.println("Yo it has been sent..");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Output:
Page No-78/98
Conclusion: The Program Successfully run and compiled
Page No-79/98
Theory -10
Windows Firewall
Theory:
The Windows Firewall is a silent tool that keeps our systems safe from all kinds of network
threats and has been included in each version of Windows for the last decade. Because it is a
silent ally, doing most of its work in the background, few users interact with it on a regular basis,
and even fewer know what this tool is and how it works. That's why, in this article, we will
explain what the Windows Firewall is, what it does, how to find it and how to enable it or disable
it, depending on whether you want to use it or not. Let's get started:
Practical : 10
Source code:
Output:
Page No-80/98
Now, if you see the firewall window shows a list of rules on the left side. From the list, select
Inbound Rules to display the inbound rules section.
Page No-81/98
Next, select „Block the connection‟ as the Action and click Next.
Page No-82/98
Later, select all the profiles available for different type of connections (Domain, Private and
Public) and Click Next to continue.
Give a name of your choice to the new rule. I used „block suspicious ports‟. If you want, you can
add the description to the new rule. This step is however optional.
Page No-83/98
Conclusion: At times, you may you may feel the need of opening a port in the Windows firewall
to let a specific IP communicate with your computer. For example, while playing games. The
procedure to open a port remains more or less the same. All you need to do is follow the
instructions in the New Inbound Rule wizard, specify the Port and select Allow the connection.
Page No-84/98
Practical 10: Example 1:
Source code:
Microsoft has been adding new security features to the Windows with every update. The
Windows 10 comes with superlative security features as opposed to the earlier versions of the
software. Firewall settings form the crux of the security feature, however, sometimes it so
happens that the Firewall blocks out a favorite app on Windows 10.
The inbuilt firewall usually works just fine and blocks out all the malicious apps and allows the
legit apps. But in some cases, users need to take control and allow their app to bypass the
firewall. Before we begin, I would like to advise you to carefully check whether an app is legit
before whitelisting it on the firewall. In this segment, we will walk you through several steps that
will help you allow or deny certain apps on the Windows 10 Firewall.
How to block a program in Windows 10 Firewall
First things first, open the Windows Defender Security Center. Select Firewall and Network
Protection.
Output:
Page No-85/98
Now click on “Allow an app through firewall”.
Click on “Change Settings” button. Make sure you have administrative privileges
Page No-86/98
From the menu Select the app that you want to allow through the Firewall. You can also add app
manually by using “Add an App” option.
Now select the type of network an app can access.
Private Network will allow the app to connect to the internet only at home or work
Public Network will allow the app to connect to the internet from anywhere including Public
WiFi hotspots
Click on OK
In order to blacklist an app or a service from the firewall all you need to do is uncheck the tick
mark against the app and also make sure you deny network access to the same. This particular
feature is extremely useful in many cases. For example, you can set your banking app to work
only in Private Network and thus safeguard yourself from the security shortcomings of a public
or unsecured WiFi.
Admins can also make changes for individual apps and this should essentially reflect on all the
other limited user accounts. This also seems to be a good way to ban certain apps on your kid‟s
account from gaining access to the network. All said and done, be very careful while handling
exceptions or changing firewall settings, if not done properly it will leave your PC vulnerable to
attacks.
Page No-87/98
Practical 10: Example 2:
Theory:
The main reason most people will ever mess with the firewall is to allow a program to work
through the firewall. Normally, this is automatically done by the program itself, but in some
cases, you have to do it manually. You can do this by clicking on Allow an app or feature
through Windows Firewall.
Output:
As you can see, for each program or feature of Windows, you can choose to allow incoming
connections on the private and public networks separately. This separation is handy for things
like File and Printer Sharing and HomeGroups since we don‟t want someone from public WiFi
to be able to connect to a network share or a local HomeGroup. To allow an app, simply find it in
the list and then check the box for which type of network you want to allow incoming
connections on.
Page No-88/98
If the app is not listed, you can click on the Allow another app button and pick from a list or
click the Browse button to find your program specifically. If the button is greyed out, click
on Change settings first.
If you go back to the Firewall home dialog, there is another link on the left-hand pane
called Turn Windows Firewall On or Off. If you click on that, you‟ll get a set of options like
shown below:
Page No-89/98
You can turn off the firewall in Windows 10 entirely, but that will allow everything through the
firewall. You can also block all incoming connections to your computer, even for allowed apps,
which is useful in certain situations. For example, if you are in a public setting like a hotel or
airport and you want to be extra safe while connected to the network. You can still browse the
Internet using a web browser, but no program will be able to create an incoming connection from
another computer on the local network or from a server on the Internet.
Page No-90/98
On the main screen, it gives you a quick overview of your firewall settings for the domain,
private networks, and public networks. If your computer is not joined to a domain, you don‟t
have to worry about that profile. You can quickly see how inbound and outbound connections
are managed by the firewall. By default, all outbound connections are allowed. If you want to
block an outbound connection, click on Outbound Rules in the left-hand column.
Go ahead and click on New Rule and then you‟ll get a dialog asking what type of rule
Page No-91/98
I chose port because I want to block all outgoing connections on port 80, the HTTP port used by
every web browser. In theory, this should block all Internet access in IE, Edge, Chrome and other
browsers. Click Next, select TCP and type in the port number.
Now just give it a name and that‟s it! When I open Chrome to visit any webpage, I get the
following error message:
Page No-92/98
Practical 10: Example 3:
Theory:
Have you ever installed a program that you only needed for offline use, but it insisted on trying
to connect to the internet? About four years ago we showed you how to allow programs through
the Windows firewall. This time around we‟re going to show you how to block them with it in
Windows 7 and 8.
If you‟re not sure which programs are accessing the internet, one easy way to find out is to open
up Windows Resource Monitor. This can be done by searching for “resmon” in the start menu, or
typing “resmon” into the Run Box (Windows Key + R). In this example I noticed that the
Everything app had networking activity and I‟m going to block it to make sure it doesn‟t send
any data away from my PC.
Output:
To get started we need to open up Windows Firewall. One quick way to do this is from the
Control Panel. Just click the Windows Firewall icon.
Page No-93/98
From the Firewall page click Advanced settings.
Here you can choose which you would like to block first: Inbound or Outbound. When it comes
down to it I think blocking Outbound is usually enough for most applications. When Outbound
connects are blocked, this means that the application can‟t send any of your data to a remote
Page No-94/98
server somewhere on the internet. Of course, if bandwidth is what you‟re worried about you
should probably block both. In any case, the process for blocking both is the same, so I‟ll just
cover one.
For the Rule Type select the “Program” bullet and click Next
Select the “This program path:” option and then either type in the path or use the browse button
to find the executable of the application
Page No-95/98
For the Action select the “Block the connection” option and click Next.
You can name the firewall rule whatever you like. It‟s a good idea to keep it something
memorable or relevant though because you may want to change or disable it later on.
Now the rule should be created and ready to go. However some applications also run as a
service, so be sure to disable that as well if you can. Right click the newly created rule and select
“Properties.”
Page No-96/98
If you want to temporarily give the application internet access again, you can disable the firewall
rule by right-clicking on it within the Advanced Firewall Security window. If you want to
permanently get rid of this blocking rule, just delete it.
Page No-97/98
Conclusion: The Program Successfully run and compiled
Page No-98/98