Information Security Manual
Information Security Manual
1
1 Department Vision, Mission, Pos and PSOs
3 Requirements 4
4 List of Experiments 5
7 Introduction to Lab 8
9 Scheme of Evaluation 55
10 References 55
Institute Vision:
To be a leading Technical Institute to prepare high quality Engineers to cater the needs
of
the stakeholders in the field of Engineering and Technology with global competence
fundamental comprehensive analytical skills, critical reasoning, research aptitude,
entrepreneur skills, ethical values and social concern.
Institute Mission:
Imparting Quality Technical Education to young Engineers by providing the state-of-the-
art laboratories, quality instructions by qualified and experienced faculty and research
facilities to meet the requirements of stakeholders in real time usage and in training
them to excel in competitive examinations for higher education and employment to
interface globally emerging techno-informative challenges in the growth corridor of
techno-excellence.
Department Vision:
To be the center of excellence in technical education with a commitment to the Nation.
Department Mission:
M1: Impart quality technical Education with State of-the-art laboratories, Analytical and
Technical Skills with standards by qualified and experienced faculty.
M3: Develop professional attitude, Critical Reasoning and technical consultancy by providing
training in cutting edge technologies.
M4: Endorse and Nurture knowledge, Life-long learning, Entrepreneurial practices, ethical
values and social concern.
1
Program Educational Objectives (PEOs):
PEO 1: To prepare the students for successful careers in Computer Science and Engineering and fulfill
the need by providing training to excel in competitive examinations for higher education and
employment.
PEO 2: To provide students a broad-based curriculum with a firm foundation in Computer Science and
Engineering, Applied Mathematics & Sciences. To impart high quality technical skills for
designing, modeling, analyzing and critical problem solving with global competence.
PEO 3: To inculcate professional, social, ethical, effective communication skills and entrepreneurial
practice among their holistic growth.
PEO 4: To provide Computer Science and Engineering students with an academic environment and
members associated with student related to professional bodies for multi-disciplinary
approach and for lifelong learning.
PEO 5: To develop research aptitude among the students in order to carry out research in cutting edge
technologies, solve real world problems and provide technical consultancy services.
Program Outcomes:
Program
Statement
Outcomes
An ability to apply knowledge of mathematics, science, and engineering and
PO1
knowledge of Fundamental Principles.
2
practice.
Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
The broad education necessary to understand the impact of engineering
PO7
solutions in a global, economic, environmental, and societal context.
PO8 An understanding of professional and ethical responsibility.
PO12 A recognition of the need for, and an ability to engage in life-long learning.
Program Specific
Statement
Outcomes
3
Course Objectives:
Explain the objectives of Information Security
Explain the importance and application of each of confidentiality, integrity, authentication and
availability
Understand various Cryptographic Algorithms
Understand the basic categories of threats to computers aqnd networks
Describe public-key cryptosystem
Describe the enhancements made to IPV4 by Ipsec
Course Outcomes:
Student will be Able to understand basic cryptographic algorithms, message and web
authentication and security issues
Ability to identify information system requirements for both of them such as client and server.
Ability to understand the current legal issue towards information security.
Requirements:
List of Experiments:
4
1. Write a C program that contains a string (char pointer) with a value ‘Hello world’. The program
should XOR each character in this string with 0 and displays the result.
2. Write a C program that contains a string (char pointer) with a value ‘Hello world’. The program
should AND or and XOR each character in this string with 127 and display the result.
3. Write a Java program to perform encryption and decryption using the following algorithms
7. Write the RC4 logic in Java Using Java cryptography; encrypt the text “Hello world” using
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.
10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
11. Calculate the message digest of a text using the MD5 algorithm in JAVA.
5
Module wise Outcomes:
11 Students can able to implement diffie helmen key exchange. 1,2,4,5 a,b,d,e,
f,k,l,m
Students can able to generate keys.
6
12 Students can able to implement SHA-1 algorithm. 1,2,4,5 a,b,c,e,
g,k.l,m
13 Students can able to implement SHA-1 algorithm to calculate 1,4,5 a,b,c,e,
g,k,m
message digest.
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 2 3 3 2 2 3
CO2 3 3 2 3 2 3
CO3 3 2 3 3 2 3 3
CO4 3 3 2 3 3 3 3 3
CO5 3 2 3 2 1 2 3 3 3 3 3
CO6 2 2 3 3 3 2 2 3 3 2 1 2 3
2.7 2.5 2.8 2.4 2.5 2.5 2.0 2.0 3.0 3.0 2.5 2.2 2.5 3.0 3.0
7
Introduction to Lab:
Computer data often travels from one computer to another, leaving the safety of its protected physical
surroundings. Once the data is out of hand, people with bad intention could modify or forge your data,
either for amusement or for their own benefit.
Cryptography can reformat and transform our data, making it safer on its trip between computers. The
technology is based on the essentials of secret codes, augmented by modern mathematics that protects
our data in powerful ways.
• Computer Security - generic name for the collection of tools designed to protect data and to
thwart hackers
• Internet Security - measures to protect data during their transmission over a collection of
interconnected networks
Program 1: XORastringwithaZero
AIM: Write a C program that contains a string (char pointer) with a value \HelloWorld’.
PROGRAM:
#include<stdlib.h>main()
{
charstr[]="HelloWorld";char
str1[11];
inti,len;len=strlen(str);f
or(i=0;i<len;i++)
{
str1[i]=str[i]^0;pri
ntf("%c",str1[i]);
8
}
printf("\n");
}
Output:
Hello World
HelloWorld
9
Program 2. XORastringwitha127
AIM: Write a C program that contains a string (char pointer) with a value \HelloWorld’.
The program should AND or and XOR each character in this string
with127anddisplaytheresult.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>voi
dmain()
{
charstr[]="HelloWorld";char
str1[11],str3[11];charstr2
[11];
inti,len;str2[i]=str[i]
;len= strlen(str);
for(i=0;i<len;i++)
{str1[i]=str[i]&127;printf("
%c",str1[i]);
printf("\n");for(i=0;i<le n;i+
+)
{ str3[i]=str2[i]^127;
printf("%c",str3[i]);}printf("
\n");
}
Output:
HelloWorld
HelloWorld
10
Program 3. Encryption&DecryptionusingCipherAlgorithms
AIM:WriteaJavaprogramtoperformencryptionanddecryptionusingthefollowingalgori
t hms:
a. CeaserCipher
b. SubstitutionCipher
c. HillCipher
PROGRAM:
Algorithm:
1. Caesarcipherisanexampleofasubstitutioncipherinwhichplaintextlettersintheoriginalmessa
ge arereplaced(substitutedfor)byciphertextletters
2. Theeasiestwaytounderstandthis istoconsiderthattherearetwoalphabets:
3. Thecipher alphabetisashiftedversionoftheplainalphabet.Inthiscase,
eachletterinthecipheralphabethas tobeshiftedby3places totheright
4. Theshift--(i.e.,thenumber 3)
isthesecretkeywhichmustbesharedbyAliceandBobiftheywanttosendsecretmessages usingthis
cipher
5. ToencryptthemessageMEETMEAT
THEDOCKwewouldreplacealltheMsinthemessagewiththecorrespondingletterfromthe
cipheralphabet
6. SoMisreplacedbyP.And
wewouldreplacealltheEsbyHandsoon.Thus,theencryptionofourmessagewouldbePHHWPHDWWL
H GRFN
11
a) CeaserCipher
importjava.io.BufferedReader;impor
tjava.io.IOException;
importjava.io.InputStreamReader;i
mportjava.util.Scanner;
publicclassCeaserCipher
staticScannersc=newScanner(System.in);
staticBufferedReaderbr= new BufferedReader(new
InputStreamReader(System.in));publicstaticvoidmain(String[]args)throwsIOException{
//TODOcodeapplicationlogichere
System.out.print("EnteranyString:");St
ringstr=br.readLine();
System.out.print("\nEntertheKey:");in
tkey=sc.nextInt();
Stringencrypted=encrypt(str, key);System.out.println("\
nEncryptedStringis:"+encrypted);
Stringdecrypted=decrypt(encrypted,key);Sys tem.out.println("\
nDecryptedStringis:"
+decrypted);System.out.println("\n");
}
publicstaticStringencrypt(Stringstr,intkey)
{
Stringencrypted="";
for(inti=0;i<str.length();i++){intc=str
.charAt(i);
if (Character.isUpperCase(c)) {
12
c=c+(key%26);
if(c>'Z')
c=c-26;
}
elseif(Character.isLowerCase(c)){
c=c+(key%26);
if(c>'z')
c=c-26;
}
encrypted+=(char)c;
}
returnencrypted;
}
publicstaticStringdecrypt(Stringstr,intkey)
{Stringdecrypted="";for(inti=0;i
<str.length();i++){intc=str.charAt(i);
if (Character.isUpperCase(c)) {
c=c-(key%26);
if(c<'A')
c=c+26;
}
13
elseif(Character.isLowerCase(c)){
c=c-(key%26);
decrypted+=(char)c;
}
returndecrypted;
}
}
Output:
EnteranyString:HelloWorldEnter
theKey:5
EncryptedStringis:MjqqtBtwqiDecr
yptedStringis:HelloWorld
b) Substitution Cipher
PROGRAM:
importjava.io.*;i
mportjava.util.*;
//TODO
codeapplicationlogichereStringa="abcdefgh
ijklmnopqrstuvwxyz";Stringb="zyxwvutsrqp
onmlkjihgfedcba";
14
System.out.print("Enteranystring:");St
ringstr=br.readLine();
Stringdecrypt="";charc
;
for(inti=0;i<str.length();i++)
{
c=str.charAt(i);in
tj=a.indexOf(c);
decrypt=decrypt+b.charAt(j);
}
System.out.println("Theencrypteddatais:"+decrypt);
}
}
Output:
Enteranystring:aceho
Theencrypted datais:zxvsl
c) HillCipherAlgorithm:
1. InaHillcipherencryption,theplaintextmessageisbrokenupintoblocksoflengthaccord
ingtothe matrixchosen
2. Eachblockof plaintextlettersisthenconvertedintoavectorof
numbersandisdottedwiththematrix
3. Theresultsarethenconvertedbacktolettersandtheciphertextmessageisproduced
4. Fordecryptionoftheciphertextmessage, theinverseofthe encryption
matrixmustbefoundOncefound,thedecryptionmatrixisthendottedwitheach -
15
blockofciphertext,producingtheplaintextmessage.
PROGRAM:
import
java.io.*;importjava.util
.*;importjava.io.*;publi
cclassHillCipher{ staticfloat[]
[]decrypt =new
float[3][1];staticfloat[][]a=newfloat[3][3
];staticfloat[][] b= new float[3][3];
staticfloat[][]mes= new float[3]
[1];staticfloat[][]res=newfloat[3] [1];
staticBufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
staticScanner sc = new
Scanner(System.in);publicstaticvoidmain(String[]args)throwsIOException{
//TODOcodeapplicationlo
gicheregetkeymes();
for(inti=0;i<3;i++)for(intj=0;j<1;j++)for(intk=0;k<
3;k++){res[i][j]=res[i][j]+a[i][k]*mes[k][j];}Sys
tem.out.print("\nEncrypted string is
:");for(inti=0;i<3;i++){ System.out.print((char)(res[i]
[0]%26+97));res[i][0]=res[i
][0];
}
inverse();
16
for(inti=0;i<3;i++)for(int
j=0;j<1;j++)for(intk=0;k<
3;k++){
decrypt[i][j]= decrypt[i][j]+b[i][k]*res[k]
[j];}System.out.print("\nDe cryptedstringis:");
for(inti=0;i<3;i++){System.out.print((char)(decrypt[i][
0]%26+97));
System.out.print("\n");
}
public static voidgetkeymes()
throwsIOException{System.out.println("Enter3x3matrixforkey(Itshouldbeinve
rsible):");for(inti=0;i<3;i++)
for(intj=0;j<3;j++)a[i][j]=s
c.nextFloat();
System.out.print("\nEntera3letterstring:");Str
ingmsg=br.readLine();
for(inti=0;i<3;i++)
mes[i][0]=msg.charAt(i)-97;
}
publicstaticvoidinverse(){floatp,q
;
float[][] c = a;for(inti=0;i<3;i+
+)f
17
or(intj=0;j<3;j++){
//a[i][j]=sc.nextFloat();
if(i==j)b[i][j]=1;
elseb[i][j]=0;
}
for(intk=0;k<3;k++){for(inti
=0;i<3;i++){
p=c[i][k];
q=c[k][k];fo
r(intj=0;j<3;j++){if(i!=k){
c[i][j]=c[i][j]*q-p*c[k][j];
b[i][j]=b[i][j]*q-p*b[k][j];
}}}}
for(inti=0;i<3;i++)for(intj=0
;j<3;j++){b[i][j]=b[i][j]/c [i]
[i];}
System.out.println("");System.out.println("\nInverse
Matrixis:");for(inti=0;i<3;i++){
for(intj=0;j<3;j++)System.out.pri nt(b[i][j]
+"");
System.out.print("\n"); }
}}
Output:
Entera3letterstring:haiEncry
ptedstringis:fdxInverseMa
trixis:
0.0833333360.41666666-0.33333334
18
-0.41666666-0.0833333360.6666667
0.5833333-0.083333336-0.33333334
Decryptedstringis:hai
Program 4:JavaprogramforDESalgorithmlogic
AIM:WriteaJavaprogramtoimplementtheDESalgorithmlogic.
Algorithm:
1. Firstly,weneedtoprocessthekey
2. Geta64- bitkeyfromtheuser.
(Every8thbitisconsideredaparitybit.Forakeytohavecorrectparity,eac
hbyteshouldcontainanoddnumberof"1"bits.)
3. Calculatethekeyschedule
4. Performthefollowingpermutationonthe64-bitkey
5. Splitthepermutedkeyintotwohalves.Thefirst28bitsarecalledC[0]andthelast28bitsarecall
edD[0]
Iteration#12345678910111213141516
LeftShifts1122222212222221
7. PermutetheconcatenationC[i]D[i]asindicatedbelow.ThiswillyieldK[i],whichis48bitslo
ng.PermutedChoice2(PC-2)
8. Loopbackto1.2.3.1untilK[16]hasbeencalculated.Processa64-bitdatablock
19
9. Get a 64-bit data block. If the block is shorter than 64 bits, it should be
paddedasappropriatefortheapplication
10. Performthefollowingpermutationonthedatablock.InitialPermutation(IP)
20
21
PROGRAM:
importjava.util.*;
importjava.io.BufferedReader;importj
ava.io.InputStreamReader;importj
ava.security.spec.KeySpec;
importjavax.crypto.Cipher;importjav
ax.crypto.SecretKey;
import
javax.crypto.SecretKeyFactory;importjava
x.crypto.spec.DESedeKeySpec;importsun.
misc.BASE64Decoder;
importsun.misc.BASE64Encoder;public
classDES{
privatestaticfinalStringUNICODE_FORMAT="UTF8";
publicstaticfinalStringDESEDE_ENCRYPTION_SCHEME="DESede";privateKe
ySpecmyKeySpec;privateSecretKeyFactorymySecretKeyFactory;
privateCiphercipher;byte[
]keyAsBytes;
privateStringmyEncryptionKey;privateStrin
gmyEncryptionScheme;SecretKeykey;
staticBufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));pub
licDES()throwsException{
//TODOcodeapplication logicheremyEncryptionKey
="ThisIsSecretEncryptionKey";myEncryptionScheme=DESEDE_ENCRYPTION_S
CHEME;keyAsBytes=
myEncryptionKey.getBytes(UNICODE_FORMAT);myKeySpec
22
=newDESedeKeySpec(keyAsBytes);
mySecretKeyFactory=SecretKeyFactory.getInstance(myEncryptionScheme);ciph
er=Cipher.getInstance(myEncryptionScheme);
key=mySecretKeyFactory.generateSecret(myKeySpec);
}
publicStringencrypt(StringunencryptedString)
{StringencryptedString=null;
try{ cipher.init(Cipher.ENCRYPT_MODE,key
);
byte[]plainText=unencryptedString.getBytes(UNICODE_FORMAT);byt
e[]encryptedText=cipher.doFinal(plainText);
BASE64Encoderbase64encoder=newBASE64Encoder();encryptedString=b
ase64encoder.encode(encryptedText);}
catch(Exceptione){e.printStackTr
ace();}returnencryptedString;
}
publicStringdecrypt(StringencryptedString)
{ String decryptedText=null;
try{ cipher.init(Cipher.DECRYPT_MODE,key
);
BASE64Decoder base64decoder = new
BASE64Decoder();byte[]encryptedText=
base64decoder.decodeBuffer(encryptedString);byte[]plainText=cipher.doFi
nal(encryptedText);decryptedText=bytes2String(plainText);}
catch(Exceptione){e.printSt
23
ackTrace();}returndecry
ptedText;}
privatestaticStringbytes2String(byte[]bytes)
{StringBufferstringBuffer=newStringBuffer();fo
r(inti=0;i<bytes.length;i++)
{stringBuffer.append((char)bytes[i]);}returnstri
ngBuffer.toString();}
publicstaticvoidmain(Stringargs[])throwsException
{System.out.print("Enterthestring:");DE
SmyEncryptor=newDES();
StringstringToEncrypt=br.readLine();
Stringencrypted=myEncryptor.encrypt(stringToEncrypt);Stringdecrypted=myEncrypto
r.decrypt(encrypted);System.out.println("\nStringToEncrypt:"
+stringToEncrypt);System.out.println("\nEncryptedValue:"+encrypted);System.o
ut.println("\nDecryptedValue:"+decrypted);System.out.println("");
}
}
OUTPUT:
Enterthestring:Welcome
StringToEncrypt:Welcome
EncryptedValue:BPQMwc0wKvg=
DecryptedValue:Welcome
24
Program 5:ProgramtoimplementBlowFishalgorithmlogic
AIM:WriteaC/JAVAprogramtoimplementtheBlowFishalgorithm logic.
PROGRAM:
importjava.io.*;
importjava.io.FileInputStream;impo
rtjava.io.FileOutputStream;impo
rtjava.security.Key;
importjavax.crypto.Cipher;
importjavax.crypto.CipherOutputStream;imp
ortjavax.crypto.KeyGenerator;
importsun.misc.BASE64Encoder;public
classBlowFish{
publicstaticvoid main(String[] args)throws Exception {
//TODOcode application
logichereKeyGeneratorkeyGenerator=KeyGenerator.getInsta
nce("Blowfish");keyGenerator.init(128);KeysecretKey=keyGe
nerator.generateKey();
Cipher cipherOut =
Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
BASE64Encoderencoder=newBASE64Encoder();
byteiv[]=
cipherOut.getIV();if(iv!=null){
FileInputStream fin=new
FileInputStream("inputFile.txt");FileOutputStreamfout=newFileOutputStre
25
am("outputFile.txt");CipherOutputStreamcout=newCipherOutputStream(f
out,cipherOut);intinput=0;
while((input=fin.read())!=-1){
fin.close();cout.close(); }}
OUTPUT:
InitializationVectoroftheCipher:dI1MXzW97
oQ=ContentsofinputFile.txt:HelloWorld
ContentsofoutputFile.txt:ùJÖ˜NåI“
26
Program 6:ProgramtoimplementRijndaelalgorithmlogic
AIM:WriteaC/JAVAprogramtoimplementtheRijndaelalgorithmlogic.
PROGRAM:
importjava.security.*;importj
avax.crypto.*;importjavax.
crypto.spec.*;importjava.i
o.*;
publicclassAES{
publicstaticString asHex (byte buf[])
{StringBufferstrbuf=newStringBuffer(buf.length*2);in
ti;
for(i=0;i<buf.length;i++){if (((int)
buf[i] &0xff)<
0x10)strbuf.append("0");
strbuf.append(Long.toString((int)buf[i]&0xff,16));}returnstrbuf.to
String();}
publicstaticvoidmain(String[]args)throwsException
{Stringmessage="AESstillrocks!!";
//GettheKeyGenerator
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");
//Instantiatethecipher
27
Ciphercipher=Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_M
ODE,skeySpec);
byte[]encrypted=cipher.doFinal((args.length==0?message:
args[0]).getBytes());System.out.println("encryptedstring:"+asHex(e
ncrypted));cipher.init(Cipher.DECRYPT_MODE,skeySpec);byte[]o
riginal=cipher.doFinal(encrypted);StringoriginalString=newStrin
g(original);
System.out.println("Originalstring:"+originalString+""+asHex(original));
}
OUTPUT:
Inputyourmessage:HelloACE
Encrypted text: 3ooo&&(*&*4r4
Decryptedtext:HelloACE
AIM:UsingJavaCryptography,encryptthe
text“Helloworld”usingBlowFish.CreateyourownkeyusingJavakeytool.
PROGRAM:
import
javax.crypto.Cipher;importjavax.cry
pto.KeyGenerator;importjavax.cryp
to.SecretKey;importjavax.swing.JO
ptionPane;publicclassBlowFishCiph
er{
28
publicstaticvoid main(String[] args)throws Exception {
//createa key generator based
upontheBlowfishcipherKeyGeneratorkeygenerator=KeyGenerator.getInstance("
Blowfish");
//createakey
//initialiseciphertowithsecretkeyciphe
r.init(Cipher.ENCRYPT_MODE,secretkey);
//getthetexttoencrypt
StringinputText=JOptionPane.showInputDialog("Inputyourmessage:
");//encryptmessage
byte[]encrypted=cipher.doFinal(inputText.getBytes());
// re-initialise the cipher to be in decrypt
modecipher.init(Cipher.DECRYPT_MODE,secretkey
);
//decryptmessage
byte[]decrypted=cipher.doFinal(encrypted);
//anddisplaytheresults
JOptionPane.showMessageDialog(JOptionPane.getRootFrame
(),
"\nEncryptedtext:"+newString(encrypted)+"\n"+"\
nDecryptedtext:"+newString(decrypted));
System.exit(0);
}}
29
OUTPUT:
Inputyourmessage:HelloworldEncryp
tedtext:3ooo&&(*&*4r4Decrypte
dtext:Helloworld
Program 8:RSAAlgorithm
AIM:ToencrypttheplaintextmessageusingRSAalgorithm.Thenperformthereverseoperation
togetoriginalplaintext.
Algorithm:
1. Generatetwolargerandomprimes,PandQ,ofapproximatelyequalsize
2. ComputeN=PxQ
3. ComputeZ=(P-1)x(Q-1)
4. ChooseanintegerE,1<E<Z,suchthatGCD(E,Z)=1
5. ComputethesecretexponentD,1<D<Z,suchthatExD≡1(modZ)
6. Thepublickeyis(N,E)andtheprivatekeyis(N,D)
AnexampleofRSAencryption:
1.SelectprimesP=11,Q=3
2. N=PxQ=11x3=33
Z=(P-1)x(Q-1)=10x2=20
3. LetschooseE=3
CheckGCD(E,P-
1) =GCD(3,10)=1(i.e.3and10havenocommonfactorsexcept1),andcheckGCD(E,
Q-1)=GCD(3,2)=1,thereforeGCD(E,Z)=GCD(3,20)=1
4. Compute Dsuchthat Ex
D≡1(modZ)ComputeD=E^-
1modZ=3^-1mod20
FindavalueforDsuchthatZdivides((ExD)-
30
1) FindDsuchthat20divides3D-
1Simpletesting(D=1,2,...)givesD=7
Check:(ExD)-1=3.7-1=20,whichisdivisiblebyZ
5. Publickey=(N,E)=(33,3)andPrivatekey=(N,D)=(33,7)
Nowsaywewanttoencryptthemessagem=7,Cipherc
ode=M^EmodN
=7^3mod33
=343mod33
=13
Hencetheciphertextc=13
TocheckdecryptionwecomputeMessage’=C^DmodN
=13^7mod33
=7
PROGRAM:
importjava.io.BufferedReader;importj
ava.io.InputStreamReader;importj
ava.math.*;
importjava.util.Random;imp
ortjava.util.Scanner;public
classRSA{
static Scanner sc = new
Scanner(System.in);publicstaticvoidmain(Strin
g[]args){
// TODO code application logic
hereSystem.out.print("EnteraPrimenum
ber:");
31
number:");BigIntegerq=sc.nextBigInteger();//..andanothe
r.
BigIntegern=p.multiply(q);
BigIntegern2=p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));B
igIntegere=generateE(n2);
BigIntegerd=e.modInverse(n2);//Here'sthemultiplicativeinverse
System.out.println("Encryptionkeysare:"+e+","+n);System.out.println("Decryptionk
eysare:"+d+","+n);
}
publicstaticBigIntegergenerateE(BigIntegerfiofn){inty,int
GCD;
BigIntegere;
BigIntegergcd;
Randomx=newRandom();
do{ y=x.nextInt(fiofn.intValue()-
1);Stringz=Integer.toString(y);
e=newBigInteger(z);gc
d=fiofn.gcd(e);
intGCD=gcd.intValue();
}
while(y<=2||intGCD!=1);ret
urne;
}
}
32
OUTPUT:
EnteraPrimenumber:5
Enteranotherprimenumber:11En
cryptionkeysare:33,55
Decryptionkeysare:17, 55
Program 9:Diffie-Hellman
AIM:ImplementtheDiffie-HellmanKeyExchangemechanism usingHTMLandJavaScript.
Consider the end user as one of the parties (Alice) and the
JavaScriptapplicationasotherparty(bob).
Algorithm:
1. Diffie-
Hellmankeyexchange(DH)isacryptographicprotocolthatallowstwopartiesthath
avenopriorknowledgeofeachother to jointly establish asharedsecretkey
2. Thealgorithmgeneratesapublickeyandaprivatekeyfortheclient
3. CreateaKeyPairGeneratorObjectthatgeneratesprivate/publickeysfortheDH
algorithm,usingthegetInstance(Stringalgortihm)APImethod
4. InitializetheKeyGeneratorsoastogeneratekeyswitha1024-
bitlength,usingtheinitialize(intkeysize)APImethod
5. CreateaKeyPairObject,withthegenKeyPair()APImethod,thatgeneratesthekey
pair.
6. CreatethePrivateKeyandPublicKeyObjects ofthekey pair,with the
getPrivate()andgetPublic()APImethodsoftheKeyPair
7. Return for both keys the names of their primary encoded formats,
33
usingforboththeirgetformat()ΑPImethods
PROGRAM:
importjava.math.BigInteger;imp
ortjava.security.KeyFactory;imp
ortjava.security.KeyPair;
importjava.security.KeyPairGenerator;impo
rt java.security.SecureRandom;
importjavax.crypto.spec.DHParameterSpec;i
mportjavax.crypto.spec.DHPublicKeySpec;p
ublic
classDiffeHellman{publicfinalstaticintpValue=47
;
publicfinalstaticintgValue=71;public
finalstaticintXaValue=9;publicfinals
taticintXbValue=14;
publicstatic void main(String[] args)
throwsException{//TODOcodeapplicationlogichere
BigIntegerp=newBigInteger(Integer.toString(pValue));BigI
ntegerg=newBigInteger(Integer.toString(gValue));BigInteg
erXa =newBigInteger(Integer.toString(XaValue));
BigIntegerXb=new BigInteger(Integer.toString(XbValue));
createKey();intbitLength=512;//512bits
SecureRandomrnd=newSecureRandom();
p=BigInteger.probablePrime(bitLength,rnd);g
=BigInteger.probablePrime(bitLength,rnd);
createSpecificKey(p,g);
34
}
publicstaticvoidcreateKey()throwsException{ KeyPairGeneratorkpg=KeyPairGenerator.getInsta
nce("DiffieHellman"
);kpg.initialize(512);
KeyPairkp=kpg.generateKeyPair();
KeyFactorykfactory=KeyFactory.getInstance("DiffieHellman");DHPublicKeySpeckspe
c=(DHPublicKeySpec)kfactory.getKeySpec(kp.getPublic(),DHPublicKeySpec.class);
System.out.println("Publickeyis:"+kspec);
}
publicstaticvoidcreateSpecificKey(BigInteger p, BigInteger g)
throwsException{KeyPairGeneratorkpg
=KeyPairGenerator.getInstance("DiffieHellman");DHParameterSpecparam=newDH
ParameterSpec(p,g);kpg.initialize(param);
KeyPairkp=kpg.generateKeyPair();
KeyFactorykfactory=KeyFactory.getInstance("DiffieHellman");DHPublicKeySpecksp
ec=(DHPublicKeySpec)kfactory.getKeySpec(kp.getPublic(),DHPublicKeySpec.class);
System.out.println("\nPublickeyis:"+kspec);
}
}
OUTPUT:
Public key is:
javax.crypto.spec.DHPublicKeySpec@5afd29Publickeyis:jav
ax.crypto.spec.DHPublicKeySpec@9971ad
35
Program 10:SHA-1
AIM:CalculatethemessagedigestofatextusingtheSHA-1algorithminJAVA.
NISTalongwiththeNSA,designedtheSecureHashAlgorithm(SHA)forusewiththeDigi
talSignatureStandard.When a message of any
length<264bitsisinput,theSHAproducesa160-
bitoutputcalledamessagedigest.SHAproducesa160-
bithash.Themessageispaddedtomakeitamultipleof512bitslong.Itprocessesthemessage512
bits at a time and continues for asmany512-bitblocksasareinthemessage.
PROGRAM:
importjava.security.*;publ
icclassSHA1{ publicstaticvoidmain(
String[]a){try{
MessageDigestmd=MessageDigest.getInstance("SHA1");Syste
m.out.println("Message
digestobjectinfo:");System.out.println("Algorithm=
"+md.getAlgorithm());System.out.println("Provider="+md.get
Provider());System.out.println("ToString="+md.toString());
Stringinput="";md.update
(input.getBytes());byte[]output=m
d.digest();System.out.println();
System.out.println("SHA1(\""+input+"\")="+bytesToHex(output));
input
="abc";md.update(input.getBytes()
);output =md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\")="+bytesToHex(output));
36
input="abcdefghijklmnopqrstuvwxyz";md.update( inpu
t.getBytes());
output=md.digest();S
ystem.out.println();
System.out.println("SHA1(\""+input+"\")="+bytesToHex(output));System.out.println("");
}
catch(Exceptione){
publicstaticStringbytesToHex(byte[]b){
charhexDigit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
StringBufferbuf = new
StringBuffer();for(intj=0;j<b.length;j++){buf.
append(hexDigit[(b[j]>>4)&0x0f]);buf.appe
nd(hexDigit[b[j]&0x0f]);}returnbuf.toString(
);}
}
OUTPUT:
Messagedigestobjectinfo:Al
gorithm=SHA1
Provider=SUNversion1.6
ToString = SHA1 Message Digest from SUN, <initialized> SHA1("")
=DA39A3EE5E6B4B0D3255BFEF95601890AFD80709SHA1("abc")=A9993E364
706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz")=32D10C7B8CF96570CA04CE37F2A19D84240D3A
37
89
Program 11:MessageDigestAlgorithm5(MD5)
AIM:CalculatethemessagedigestofatextusingtheSHA-1algorithminJAVA
Algorithm:
1. Appendpaddedbits-
Themessageispaddedsothatitslengthiscongruentto448,modulo512.Meansextend
edtojust64bitsshyofbeingof512bitslong.–
Asingle“1”bitisappendedtothemessage,andthen“0”bitsareappendedsothatthelen
gthinbitsequals448modulo512
2. Appendlength-
A64bitrepresentationofbisappendedtotheresultofthepreviousstep.Theresultingm
essagehasalengththatisanexactmultipleof512bits
3. Initialize MD Buffer - A four-word buffer (A,B,C,D) is used to compute
themessagedigest.–
HereeachofA,B,C,D,isa32bitregister.Theseregistersareinitializedtothefollowin
gvaluesinhexadecimal:wordA: 01234567wordB:89abcdefwordC:
fedcba98wordD:76543210
4. Process message in 16-word blocks – Four auxiliary functions that take as
inputthree32-bitwordsandproduceasoutputone32-
bitword.F(X,Y,Z)=XYvnot(X)ZG(X,Y,Z) =XZvYnot(Z)H(X,Y,Z) =XxorYxorZI(X,Y,Z)
=Yxor(Xvnot(Z))Processmessagein16-wordblockscont–
ifthebitsofX,Y,andZareindependentandunbiased,theeachbitofF(X,Y,Z),G(X,Y,Z),H( X,Y,Z),an
dI(X,Y,Z)willbeindependentandunbiased
38
PROGRAM:
importjava.security.*;publ
icclassMD5{ publicstaticvoidmain(S
tring[]a){
//TODOcodeapplicationlogichere
try{ MessageDigestmd=MessageDigest.getInstance("MD5");System.out.println(
"Me ssagedigestobjectinfo:");
System.out.println("Algorithm="+md.getAlgorithm());System.out.pri
ntln("Provider="+md.getProvider());System.out.println("ToString="+
md.toString());
Stringinput="";
md.update(input.getBytes());
byte[]output=md.digest();S
ystem.out.println();
System.out.println("MD5(\""+input+"\")="+bytesToHex(output));
input
="abc";md.update(input.getBytes()
);output
=md.digest();System.out.println();
System.out.println("MD5(\""+input+"\")="+bytesToHex(output));
input="abcdefghijklmnopqrstuvwxyz";md.update( inpu
t.getBytes());
output=md.digest();S
ystem.out.println();
System.out.println("MD5(\""+input+"\")="
39
+bytesToHex(output));System.out.println("");
}
catch(Exceptione)
{System.out.println("Exception:"+e);}
}
publicstaticStringbytesToHex(byte[]b){
charhexDigit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
StringBufferbuf = new
StringBuffer();for(intj=0;j<b.length;j++){buf.
append(hexDigit[(b[j]>>4)&0x0f]);buf.appe
nd(hexDigit[b[j]&0x0f]);}
returnbuf.toString();}}
OUTPUT:
Messagedigestobjectinfo:Al
gorithm=MD5
Provider=SUNversion1.6
ToString=MD5MessageDigestfromSUN,<initialized>MD5("")=D41D8CD98F00B2
04E9800998ECF8427EMD5("abc")=
900150983CD24FB0D6963F7D28E17F72MD5("abcdefghijklmnopqrstuvwxyz")=
C3FCD3D76192E4007DFB496CCA67E13B
40
VIVA QUESTIONS:
Q1. What is Cryptography?
Q5. What is the difference between a private key and a public key?
Q8. What are the specific components of the Public Key Infrastructure (PKI)?
Q20. How is RSA used for authentication in practice? What are RSA digital signatures?
41
Q27. What is a group signature?
Q30.What is Skipjack?
Q40. Cryptographically speaking, what is the main method of building a shared secret over a public
medium?
Q43. If you had to both encrypt and compress data during transmission, which would you do first,
and why?
Q44. What is SSL and why is it not enough when it comes to encryption?
Q47. What is the Three-way handshake? How can it be used to create a DOS attack?
42
Additional Experiments-beyond syllabus:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define MX 5
int i,j,w,x,y,z;
FILE *out;
if((out=fopen("cipher.txt","a+"))==NULL)
printf("File Currupted.");
for(i=0;i<MX;i++)
for(j=0;j<MX;j++)
if(ch1==key[i][j])
w=i;
x=j;
else if(ch2==key[i][j])
43
{
y=i;
z=j;
}}}
//printf("%d%d %d%d",w,x,y,z);
if(w==y)
{ x=(x+1)%5;z=(z+1)%
5;
printf("%c%c",key[w][x],key[y][z]);
fprintf(out, "%c%c",key[w][x],key[y][z]);
else if(x==z)
{ w=(w+1)%5;y=(y+1)%
5;
printf("%c%c",key[w][x],key[y][z]);
fprintf(out, "%c%c",key[w][x],key[y][z]);
else
printf("%c%c",key[w][z],key[y][x]);
fprintf(out, "%c%c",key[w][z],key[y][x]);
fclose(out);
void main()
int i,j,k=0,l,m=0,n;
44
char key[MX][MX],keyminus[25],keystr[10],str[25]={0};
char
alpa[26]={'A','B','C','D','E','F','G','H','I','J','K','L'
,'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}
clrscr(); printf("\
nEnter key:");
gets(keystr);
gets(str);
n=strlen(keystr);
if(keystr[i]=='j')keystr[i]='i';
else if(keystr[i]=='J')keystr[i]='I';
keystr[i] = toupper(keystr[i]);
if(str[i]=='j')str[i]='i';
else if(str[i]=='J')str[i]='I';
str[i] = toupper(str[i]);
j=0;
for(i=0;i<26;i++)
45
{
for(k=0;k<n;k++)
if(keystr[k]==alpa[i])
break;
else if(alpa[i]=='J')
break;
if(k==n)
keyminus[j]=alpa[i];j++;
k=0;
for(i=0;i<MX;i++)
for(j=0;j<MX;j++)
if(k<n)
key[i][j]=keystr[k]; k+
+;}
else
key[i][j]=keyminus[m];m++;
46
printf("%c ",key[i][j]);
printf("\n");
for(i=0;i<strlen(str);i++)
if(str[i]=='J')str[i]='I';
if(str[i+1]=='\0')
playfair(str[i],'X',key);
else
if(str[i+1]=='J')str[i+1]='I';
if(str[i]==str[i+1])
playfair(str[i],'X',key);
else
playfair(str[i],str[i+1],key);i++;
}}
getch();
47
PROGRAM 2:C program to implement Vigenere Cipher
#include <stdio.h>
#include<conio.h>
#include <ctype.h>
#include <string.h>
void encipher();
void decipher();
void main()
int choice;
clrscr();
while(1)
scanf("%d",&choice);
if(choice == 3)
exit(0);
else if(choice == 1)
encipher();
else if(choice == 2)
decipher();
else
48
}
void encipher()
char input[50],key[10];
scanf("%s",input); printf("\
scanf("%s",key);
for(i=0,j=0;i<strlen(input);i++,j++)
if(j>=strlen(key))
{ j=0;
printf("%c",65+(((toupper(input[i])-65)+(toupper(key[j])-
65))%26));
}}
void decipher()
char input[50],key[10];
int value;
scanf("%s",input);
49
scanf("%s",key);
for(i=0,j=0;i<strlen(input);i++,j++)
if(j>=strlen(key))
{ j=0; }
value = (toupper(input[i])-64)-(toupper(key[j])-64);
}}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
int i,j,k,l;
char a[20],c[20],d[20];
clrscr();
gets(a);
l=strlen(a);
/*Ciphering*/
for(i=0,j=0;i<l;i++)
50
{
if(i%2==0)
c[j++]=a[i];
for(i=0;i<l;i++)
if(i%2==1)
c[j++]=a[i];
} c[j]='\
0';
printf("\n%s",c);
/*Deciphering*/
if(l%2==0)
k=l/2;
else
k=(l/2)+1;
for(i=0,j=0;i<k;i++)
d[j]=c[i];
j=j+2;
for(i=k,j=1;i<l;i++)
d[j]=c[i];
j=j+2;
51
d[l]='\0';
printf("%s",d);
getch();
PROGRAM :
#include<iostream>
#include <string>
class vernam
char enc[1000],dec[1000];
vernam(string a, string b)
s = a;
k = b;
void encrypt()
+)
enc[i] = s[i]^k[j];
j++;
52
if(j>=k.size())
j =0;
void decrypt()
+)
dec[i] = enc[i]^k[j];
j++;
if(j>=k.size())
j =0;
void printenc()
int i;
char c;
for(i=0;i<s.size();i++)
c = enc[i]%74 + 48;
cout<<c;
53
}
cout<<endl;
void printdec()
int i; for(i=0;i<s.size();i+
+)
{
cout<<dec[i];
cout<<endl;
};
int main()
string s,k;
getline(cin,s);
getline(cin,k);
vernam v(s,k);
v.encrypt();
v.printenc();
cout<<endl;
v.decrypt();
v.printdec();
54
system ("pause");
return 0;
Scheme of Evaluation:
Internal Assessment
Total Marks 25
External Assessment
1 Write up 25
2 Experimentation 25
3 Viva 25
Total Marks 75
References:
1. Cryptography and Network Security: C K Shyamala, N Harini, Dr T R Padmanabhan, Wiley India, 1st
Edition.
2. Cryptography and Network Security: Forouzan Mukhopadhyay, Mc Graw Hill, 3rd Edition
3. Information Security, Principles, and Practice: Mark Stamp, Wiley India.
4. Principles of Computer Security: WM. Arthur Conklin, Greg White, TMH
5. Introduction to Network Security: Neal Krawetz, CENGAGE Learning
6. Network Security and Cryptography: Bernard Menezes, CENGAGE Learning
55
56