CN&CT_STAFF

156
EXPNO : 1(a) AIM: To write a program to implement Bit-Stuffing DESCRIPTON: This program is used for stuffing the bits.when there are five consecutive ones in given string it stuffs zero after them.while decrypting the zero’s are removed.This process is continued for entire given string. ALGORITHM : 1) Start 2) Take a flag type array and initialize it with string “01111110” 3) Initialize count to zero and ln to zero 4) Read the bit stream of the frame to an array a 5) Concat the strings temp and flag 6) Initialize i to 0 7) If i less than string length of a a) if a[i]==1 i. increament the count ii. ln is made equal to string length of temp iii. temp of ln is made equal to a[i] iv. if count is equal to 5 ln is equal to string length of temp temp of ln is equal to ’0’ Count =0 b) else i. count=0 ii. ln is assigned to string length of temp iii. temp is assigned to a[i] c) i++ goto 7(a) and check the condition and continue 8) Concat the strings temp, flag 9) Concat the strings a and temp 10) Print string after the bit stuffing 11) Stop

Transcript of CN&CT_STAFF

Page 1: CN&CT_STAFF

EXPNO: 1(a)AIM: To write a program to implement Bit-StuffingDESCRIPTON: This program is used for stuffing the bits.when there are five consecutive ones in given string it stuffs zero after them.while decrypting the zero’s are removed.This process is continued for entire given string.ALGORITHM:1) Start2) Take a flag type array and initialize it with string “01111110”3) Initialize count to zero and ln to zero4) Read the bit stream of the frame to an array a5) Concat the strings temp and flag6) Initialize i to 07) If i less than string length of a

a) if a[i]==1i. increament the count

ii. ln is made equal to string length of tempiii. temp of ln is made equal to a[i]iv. if count is equal to 5

ln is equal to string length of temptemp of ln is equal to ’0’Count =0

b) elsei. count=0

ii. ln is assigned to string length of tempiii. temp is assigned to a[i]

c) i++goto 7(a) and check the condition and continue

8) Concat the strings temp, flag 9) Concat the strings a and temp 10) Print string after the bit stuffing 11) Stop

Page 2: CN&CT_STAFF

PROGRAM:/***********************************************************************

To implement Bit-stuffing***********************************************************************/#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char a[50], flag[]=”01111110”; int count=0,ln=0,I; clrscr(); printf(“Enter bit stream (0,1) of frame”); /* reading bits */ gets(a); strcat(temp,flag); for(i=0;i<strlen(a);i++) { count=0; ln=strlen(temp); if(a[i]= =’1’) { /* counting number of ones*/ count++; ln=strlen(temp); temp[ln]=a[i]; if(count==5) { ln=strlen(temp); /* appending zero in ones */ temp[ln]=’0’; } } else { temp[ln]=a[i]; } } } strcat(temp.flag); strcpy(a,temp); printf(“\nAfter bit stuffing the frame”); /* printing the stuffed bits */ puts(a); getch();}

Page 3: CN&CT_STAFF

INPUT/OUTPUT:

1) Enter the bit stream(0,1) of the frame0111000011101

After the bit stuffing the frame is 011111100111000011101011111102) Enter the bit stream(0,1) of the frame 01111101111110 After the bit stuffing the frame is 01111110011111001111101001111110

CONCLUSION: The output is correct and the program is error free

VIVA QUESTIONS: 1) what is bit stuffing? Ans ) After consecutive five ones insert zero. Ex) 0100111111110 01001111101110

Page 4: CN&CT_STAFF

EXPNO: 1(b)

AIM: To write a program to implement character stuffing.DESCRIPTION: This program is used for stuffing the characters. In the input data if DLE exists we stuff another DLE in the data. For starting and ending of data we use DLESTX and DLEETX respectively.while decrypting we remove the stuffed DLE.ALGORITHM:

1) start2) Initialize a character type array ‘test’ to “DLE”3) Initialize the string ‘stx’ with “DLESTX”4) Initialize the string ‘end’ with “DLEETX”5) Copy the string stx to t6) Read the input value to n7) Read the string to an array8) initialize i to 09) if i< n repeat the following steps a) if the strings input and test are equal, then concatenate the string test to t b) concatenate string input to t c) concatenate the string end to t d) print the string t e) copy the string stx to t10) stop

Page 5: CN&CT_STAFF

PROGRAM:

/*PROGRAM TO IMPLEMENT CHARACTER STUFFING*/

#include<stdio.h>#include<conio.h>#include<string.h> void main() { char input[10][10]; /* declaration and initialization of variables*/ int i, n; char stx[10]=”DLESTX”; char end[10]=”DLEETX”; char t[50],test[25]=”DLE”; clrscr(); strcpy(t,stx); printf(“enter the input value for n”); /* read n value*/ scanf(“%d”,&n); for(i=0;i<n;i++) { printf(“enter the string %d”,i); /*read n strings*/ fflush(stdin”); gets(input[i]); } printf(“after character stuffing”); for(i=0i<n;i++) { if(strcmp(input[i],test)==0) /*verify if input is same as DLE*/ strcat(t,input[i]); strcat(t,end); fflush(stdin); printf(“%s”,t); printf(“\n”); strcpy(t,stx); } getch();}

OUTPUT:

1) Enter the input value for n 4 Enter the string ABCFIC Enter the string CILM Enter the string DLE Enter the string ABDLECN After character stuffing

Page 6: CN&CT_STAFF

DLESTXABCFICDLEETX DLESTXCILMDLEETX DLESTXDLEDLEDLEETX DLESTXABDLECNDLEETX2) Enter the input value for n 1 Enter the string 12345 After character stuffing DLESTX12345DLEETX

CONCLUSION: the output is correct and hence the program is error free.

VIVA QUESTIONS: 1) What are design issues of data link layer? Ans) services provided to upper layers, framing, error control, flow control.

Page 7: CN&CT_STAFF

Exp.No:2(a)

Aim:To write a program to implement CRC Encoding algorithm Description: (CYCLIC REDUNDANCY CHECK)This program is used for encoding the given bits using the generated string. The encoded information is transmitted to the other end.For encoding we perform the exclusive operation.Algorithm: 1)Start 2)Read the frame string to cg 3)Read the generated string to cg 4)for the entire string length of cg a) Concatenate the string 0 to cp 5)print the cp 6)for the entire string length of cp a)calculate p[i]as cp[i]-‘0’ 7)for the entire string length of cg a)calculate g[i]ascg[i]-‘0’ 8)Initialize i and j to zero 9)while(1) a)Initialize j to zero b)While p[j] is not equal to 1 i)Increment j ii)if j is grater than strlen(cp)-(strlen(cg)-1) then do 1)goto step a iii)Initialize k to zero iv)for i=j to j+strlen(cg) step i and step k 1)p[i]=p[i]^g[k] 10)for i=strlen(cp)-1 to strlen(cp)-(strlen(cg)-1) step down i a)cp=p[i]-‘0’ 11)Print cp which has the data to be transmitted 12)Stop

Page 8: CN&CT_STAFF

Program: /********program to implement CRC encoding**********/ #include<stdio.h> #include<conio.h> #include<string.h> void main() { static int p[20],g[20]; int I,j,k; char cp[20],cg[20]; clrscr(); printf(“enter the frame string”); /* reading strings*/ gets(cp); printf(“enter the generated string”); gets(cg); for(k=0;k<strlen(cg)-1;k++) strcat(cp,”0”); for(i=0;i<strlen(cp);i++) p[i]=cp[i]-‘0’; for(i=0;i<strlen(cg);i++)/* removing zeros*/ g[i]=cg[i]-‘0’; printf(“\n”); i=0; j=0; while(1) { j=0; while(p[j]!=1)/* check until 1*/ j++ ; if(j>=strlen(cp)-(strlen(cg)-1)) break; k=0; for(i=j;i<j+strlen(cg);i++,k++ ) p[i]=p[i]^g[k];/* doing exclusive or operation*/ } printf(“the database transmitted is:”); for(i=strlen(cp)-1);i>=strlen(cp)-strlen(cg)-1);i--) cp[i]=p[i]+'0’; /* appending zeros */ printf(“%s”,cp); getch(); } /**************END OF PROGRAM*****************/

Page 9: CN&CT_STAFF

INPUT/OUTPUT: 1)enter the frame string: 11101100 enter the generator string: 1101 the database transmitted is:11101100110 2) enter the frame string:110011010 enter the generator string:1101 the database transmitted is:1100110011011 3) enter the frame string:1011001010 enter the generator string:1101 the database transmitted is:10011001100110

CONCLUSION: The output is correct and hence the program is error free.

Page 10: CN&CT_STAFF

EXP NO:2(b)AIM: To implement the crc decoding algorithm.DESCRIPTION:This program is used for decoding the string which is encoded in the CRC encoding algorithm. Also we check for the errors that occur in the transmited data. For this we use exclusive operation.ALGORITHM:

1. Start.2. read the received string in cp.3. read the generating string cg.4. for all the values from 0 to the whole length of cp do

p[i]=cp[i]-‘0’.5. for all the values from 0 to the whole length of cg do g[i]=cg[i]-‘0’. 6. initialize i and j to zero.

7. a. initialize j to zero. b. increment j until cp[j] is equal to 1. c. if (j>=strlen(cp)-strlen((cg)-1) then goto step 8 d. initialize k to zero. e. from j to j+strlen(cg) do p[i]=p[i]^g[k] increment i and k.8. for i is zero to strlen(cp) check if cp[i] is not equal to zero break.

9. a. if I is equal to strlen(cp) then do i. then write there is no error. ii. write the data received is iii. for i from 0 to strlen(cp) then print cp[i]-‘0’. b. if I is not equalto strlen(cp) then write there is an error.

10.Stop.

Page 11: CN&CT_STAFF

PROGRAM: #include<stdio.h> #include<conio.h> #include<math.h> #include<string.h> main() { static int p[20],g[20]; int i,j,k; char cp[20],cg[20]; clrscr(); printf(“crc received string:”); /*reading recived string */ gets(cp); printf(“enter the polynomial string:”); gets(cg);

for(i=0;i<strlen(cp);i++) p[i]=cp[i]-‘0’; for(i=0;i<strlen(cg);i++) g[i]=cg[i]-‘0’; i=0; j=0; while(1) { j=0; while(p[j]!=1) j++; if(j>strlen(cp)-(strlen(cg)-1)) break; k=0; for(i=j;i<j+strlen(cg);i++,k++) p[i]=p[i]^g[k]; /* dong exclusive or operation */ } for(i=0;i<strlen(cp);i++) /* checking for errors */

if(p[i]!=0) break; if(i==strlen(cp)) { printf(“\n No errors”); printf(“\n The Data received is :”); for(i=0;i<strlen(cp)-(strlen(cg)-1);i++) printf(“%d”,cp[i]-‘0’); /* printing decoded string */ } else printf(“\n ERROR”); /* reporting errors */

Page 12: CN&CT_STAFF

getch();}

INPUT/OUTPUT:1. crc received string : 11010110111110 Enter the polynomial string 10011 No errors.

The data received is : 11010110112. crc received string is : 1110001010 Enter the polynomial string 11010 ERROR.3. crc received string : 101010110 Enter the polynomial string 10001 No errors

The data received is : 111000010.

CONCLUSION: Hence the program is error free.

VIVA QUESTIONS: 1)CRC is mainly used for?

Ans) Error detection

2)what are different error correction methods? Ans) Hammming code ,parity check etc.

Page 13: CN&CT_STAFF

EXPERIMENT NO: 3AIM: To write a C program to implement the dijsktra’s algorithm.DESCRIPTION: This program is used for finding the shortest path between nodes.Path is found based on the cost of the path existing between the nodes. Among different paths it selects the minimum path between source and destination. ALGORITHM:

1. Start.2. Read the number of nodes to n.3. Read all the distances to matrix ‘mat’.4. Read the source to variable ‘sor’.5. vnod[v++]=sor6. Read the destination to des7. a. cou is incremented . b. assign visit to zero. c. assign 1000 to small. d. for j from 0 to n incrementing j in steps of 1 and assigning visit to zero repeat the following steps. If mat[sor][j]<small && mat [sor][j]!=0then do the following: for k from 0 to v-1 do if j=vnod[k] assign 1 to visit if visit!=1 do small=mat[sor][j] assign j to sor vnod[v++]=sor if sor=des then break e.if sor is not equal to des or cou=n then goto step a otherwise goto step 9.9. Print the path-vnod[0]+65.10. for i=1 to v print the vnod[1]+65.11. Stop.

Page 14: CN&CT_STAFF

PROGRAM:/* to implement dijsktra’s algorithm */#include<stdio.h>#include<conio.h>void main(){ int mat[10][10]; int n=8,sor,des,small=1000,vnod[10]={-1},v=0,cou=0; int visit=0,I,j,k; clrscr( ); printf( “ enter the no. of nodes\n”); /* reading no. of nodes */ scanf(“%d”,&n); printf(“enter the distances\n”); /* reading distances */ for(i=0;i<n;i++) { for(j=0;j<n;j++) { scanf(“%d”,&mat[i][j]); } } printf(“distances \n”); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf(“%d”,mat[i][j]); } printf(“\n”); } printf(“enter the source”); /*reading source */ scanf(“%d”.&sor); vnod[v++]=sor; printf(“\n enter the destination \n”); /* reading destination */ scanf(“%d”,&des); do { cou++ ; visit=0; small=1000; for(j=o;j<n;j++,visit=0) if(mat[sor][j]<small && mat[sor][j]!=0) { for(k=0;k<v-1;k++) if(j = = vnod[k]) visit=1; /* marking nodes */ if(visit!=1)

Page 15: CN&CT_STAFF

{ small=mat[sor][j]; sor=j; vnod[v++]=sor; if(sor==des) Break; } } }while(sor!=des | | cou==n); /* until source equals to destination */ print(“the path is \n”); printf(“%c”,vnod[0]+65); for(i=1;i<v;i++) Printf(“%c” vnod[i]+65); /* printing path */ getch( ); }

INPUT/OUTPUT:1. enter no. of nodes 4 enter distances 0 3 5 4 3 0 1 0 5 1 0 3 4 0 3 0

the distances are0 3 5 4 3 0 1 0 5 1 0 3 4 0 3 0enter the source0enter the destination2the path isA-->B-->C

CONCLUSION: The output is correct and hence the program is error-free.

VIVA QUSTIONS: 1)Is shortest path routing algorithm either static or dynamic routing algorithm ?Ans) static2) which principle is used in shortest path routing algorithm ?Ans) Dijkstra’s

Page 16: CN&CT_STAFF

EXPNO:4AIM: To write a program for implementing the Distance Vector Routing AlgorithmDESCRIPTION: This program is used for finding the shortest path between source and destination using time delays. The path is selected based on the minimum time delay of the adjacent vertices. The time delays for all the nodes are read as input.ALGORITHM:

1) start2) read the number of vertices to nv3) read the source vertex name and number to sv and sn4) read the number of adjacent vertices to noadj5) for each I from 0 to noadj read the time delay to adj node and the name of that node to edel[i] and adver[i]6) for each I from 0 to noadj

read the time delay from adver[i] to all the other nodes to tdel[i] j varies from 0 to nv

7) for each I from 0 to nvmin=1000ch=0

a)for each j from 0 to noadj if min>tdel[j][i]+edel[j] then

min=tdel[j][i]+edel[j] ch=adver[j] if i!=sv-1 then write i+1 ch,min else Write i+18) stop

Page 17: CN&CT_STAFF

PROGRAM:To implement Distance Vector Routing Algorithm:

#include<stdio.h>main(){ int i,j,k,nv,noadj,edel[20],tdel[20][20],min; char sn,adver[20],ch; clrscr(); printf(“\n Enter the number of vertices:”); /* reading vertices */ scanf(“%d”,&nv); printf(“Enter the number of adjacent vertices to the vertex %c :”,sn); /* enter the adjacent vertices*/ scanf(“%d”,&noadj); for(i=0;i<noadj;i++) {

printf(“\n Enter time delay to adj node %d and node name of adj node %d:”,i+1,i+1); /* reading time delay and node name*/ scanf(“%d%c”,&edel[i],&adver[i]); } for(i=0;i<noadj;i++){ printf(“\nEnter the time delay from %c to all other nodes:”,adver[i]); for(j=0;j<nv;j++) scanf(“%d”,&tdel[i][j]);}printf(“\n Destination Node \t Adjacent Node \t Shortest Delay”); for(i=0;i<nv;i++) { min=1000; ch=0; for(j=0;j<noadj;j++) if(min>tdel[j][i]+edel[j])) /* finding the shortest path */ { min=tdel[j][i]+edel[j]; ch=adver[j]; } if(i!=sv-1) printf(“\n %d \t \t %d”,i+1,ch,min); else printf(\n %d-0 »,i+1) ; }getch();}

Page 18: CN&CT_STAFF

INPUT/OUTPUT: Enter number of vertices: 12Enter source vertex and name: 10jEnter number of adjacent nodes to the source vertex: j 4Enter time delay to adjacent node 1 and node name of adjacent node: 1 8aEnter time delay to adjacent node 2 and node name of adjacent node: 2 10iEnter time delay to adjacent node 3 and node name of adjacent node: 3 12hEnter time delay to adjacent node 4 and node name of adjacent node:4 9kEnter time delay from a to all other nodes: 0 12 25 40 14 23 18 17 21 9 24 29Enter time delay from i to all other nodes: 24 36 18 27 7 20 0 11 22 23Enter time delay from h to all other nodes: 20 31 19 8 30 19 6 0 14 7 22 9Enter time delay from k to all other nodes: 21 28 36 24 22 40 31 19 22 10 0 9

Destination Node Adjacent Node Shortest Delay1 a 82 a 203 i 284 h 205 i 176 i 307 h 188 h 129 i 1010 – 011 k 912 k 18

CONCLUSION:The output is correct and hence the program is error free.

VIVA QUESTIONS: 1) Is distance vector routing algorithm static or dynamic? Ans) dynamic2) what are another names to distance vector routing algorithm? Ans) Bell man Ford, Ford fulkerson

Page 19: CN&CT_STAFF

EXPNO: 5

AIM: To write a program for implementation of hierarchical routing Algorithm.DESCRIPTION: This program is used for finding the shortest between the source and destination . The shortest path is selected based on the number of hops existing between the nodes. The program displays the path to the other region and hops required for that going to that region.ALGORITHM:

1) start2) read number of vertices no3) read the source vertex to sv4) read full table for source vertex sv5) initialize i to 06) if i<no, repeat the following steps a) read f[i].dest, f[i].line, f[i].hops b) increment i by 17) initialize i to 08) if i<no repeat the following steps a) if sv[0]==f[i].dest[0] write f[i].dest, f[i].line, f[i].hops increment i b) else initialize min to 0, minver to 0 assign f[i].dest[0] to temp while temp is equal to dest[0] repeat the following if min>f[i].hops then min=f[i].hops minver=i increment i write temp, f[minver].line, f[minver].hops

Page 20: CN&CT_STAFF

PROGRAM:

#include<stdio.h>#include<conio.h>struct full /*declaration of structure full */{ char line[10],dest[10]; int hops;}f[20];

void main(){ int nv,min ,minver,I; char sv[2],temp; clrscr(); printf(“enter no. of vertices”); /* reading vertices */ scanf(“%d”,&nv); printf(“enter source vertex”); /* reading source vertex */ scanf(“%s”,sv); printf(“enter full table for soutce vertex %s”,sv); /* reading distances */ for(i=0;i<no;i++) scanf(%s%s%d”,f[i].dest,f[i].line,&f[i].hops); printf(“\n HIERARCHICAL TABLE\n”); for(i=0;i<nv;) { if(sv[0]==f[i].dest[0]) { printf(“\n%s%s%d”,f[i].dest,f[i].line,f[i].hops); i++; } else { min=1000; minver=0; while(temp==f[i].dest[0]) /* calculating the minimum distances */ { if(min>f[i].hops) { min=f[i].hops; minver=i; } i++; } printf(“\n%c%s%d”,temp,f[minver].line,f[minver].hops);

}

Page 21: CN&CT_STAFF

} getch();}

OUTPUT:1) enter no. of vertices 17 Enter source vertex 1a Enter full table for source vertex 1a 1a 0 0 1b 1b 1 1c 1c 1 2a 1c 2 2b 1c 3 2c 1c 4 2d 1c 3 3a 1c 2 3b 1c 3 4a 1c 4 4b 1c 5 4c 1c 5 5a 1c 5 5b 1c 5 5c 1c 4 5d 1c 5 5e 1c 6HIERARCHICAL TABLE

1a 0 01b 1b 1 1c 1c 1 2 1c 23 1c 2 4 1c 45 1c 5

CONCLUSION: hence the program is error free.

VIVA QUESTION: 1) what are advantages of hierarchical routing algorithm? Ans) memory space reduced , time complex reduced,line bandwidth utilized effectively.

2) what are properties of routin algorithm? Ans) simplicity ,fairness ,optimality, robustness, stability.

Page 22: CN&CT_STAFF

6 Aim: Write a program for DES encryption process

Description:

DES is the most widely used block cipher in world. It was adopted in 1977 by NBS (now NIST) as FIPS PUB 46. It encrypts 64-bit data using 56-bit key. The following diagram gives the complete structure of DES Encryption.

FlowChart:

Page 23: CN&CT_STAFF

The following diagram gives the internal structure of a round in DES Encryption.

The following diagram gives the mechanism of compression using S-boxes.

Page 24: CN&CT_STAFF

Algorithm: 1)start 2)repeat a)ask to enter the required choice of either data encryption or data decryption or to exit b)read the choice of above to variable choice c) i)if the choice is data encryption 1)write data encryption 2)read the plain text to array plain 3)read encryption key to half size of the plain text to array key 4)assign the length of p to lp 5)initialize j as 0 6)for each i from 0 to plain[i]!=’\0’ a)if lp> i then do i)cipher[i]=plain[i]^key[i] b) else i)cipher[i]=plain[i]^key[i] 7)assign ‘\0’ to cipher[i] 8)write the encrypted text which is cipher 9)goto i ii) 1)write data decryption 2)initialize j as 0 6)for each i from 0 to cipher[i]!=’\0’ a)if lp> i then do

Page 25: CN&CT_STAFF

i)plain[i]=cipher[i]^key[i] b) else i)plain[i]=cipher[i]^key[i] 7)assign ‘\0’ to plain[i] 8)write the decrypted text which is in plain 9)goto i iii)goto c iv)defaultly write this as an invalid operation 3)stop

Page 26: CN&CT_STAFF

Program:/***********program to implement DES algorithm**************/ #include<stdio.h>#include<conio.h>#include<string.h>void main(){ char cipher[50],plain[50]; char key[50]; int choice,I,lp,j; clrscr(); while(1) { printf(“---------menu----------“); /* reading choices for user to do encryption or decryption */ printf(“1.data encryption\n2.data decryption\n3.exit”); printf(“enter your choice”); scanf(“%d”,&choice); switch(choice) { case 1: printf(“DATA ENCRYPTION”); printf(“enter the plain text”); fflush(stdin); gets(plain); printf(“enter the encryption key with half the size of plain textr”); gets(key); lp=strlen(key); j=0; for(i=0;plain[i]!=’\0’;i++) { if(lp>i) cipher[i]=plain[i]^key[i]; /* doing exclusive or operation */ else { cipher[i]=plain[i]^key[j]; j++; } } cipher[i]=’\0’; /* appending \0*/ printf(“the encryption text is:”); puts(cipher); break; case 2: printf(“DATA DECRYPTION”); j=0;

Page 27: CN&CT_STAFF

for(i=0;cipher[i]!=’\0’;i++) { if(lp>i) plain[i]=cipher[i]^key[i]; /* doing exclusive or operation*/ else { plain[i]=cipher[i]^key[j]; j++; } } plain[i]=’\0’; /* appending \0 */ printf(“the decryption text is:”); puts(plain); break;

case 3:exit(0); default:printf(“invalid operation”); } } getch(); }/***********end of program***********/

Page 28: CN&CT_STAFF

INPUT/OUTPUT: --------menu-------- 1)data encryption 2)data decryption 3)exit Enter your choice 1 Data encryption Enter the plaintext GUDLAVALLERU GEC Enter the encryption key with half size of plain text 1 2 3 4 5 6 7 8 The encryption text is :VUVLRVULYEDU|G]R --------menu-------- 1)data encryption 2)data decryption 3)exit Enter your choice 2The decrypted data is:GUDLAVALLERU GEC --------menu-------- 1)data encryption 2)data decryption 3)exitEnter your choice 3

Viva:-

1) What is the full form of DES?Ans) Data Encryption Standard

2) What is the key length of DES?Ans) 56-bit

3) How many rounds are there in DES?Ans) 16

4) How many S-boxes are there in DES?Ans) 8

5) Does the DES Encryption is reverse of Decryption or not?Ans) Sub-keys will be used in the reverse order.

6) Is it vulnerable for cryptanalytic attacks or not?Ans) Yes

Page 29: CN&CT_STAFF

Exp. No: 7 (a).

Aim: To implement program to generate key for RSA algorithm

Descriptiom:The program implemented generates the key for the RSA algorithm. The

public key and private key are generated by this algorithm. The p and q which are two prime numbers are accepted from the user and the Euler totient and n value are calculated. the e values are then calculated by the GCD (eq,i),where eq is euler totient and I is value upto eq, when the function evaluates to 1 the e value is printed the user then selects the e value based upon which the d value is calculated the d value is calculated by the formula d=(k*eq+1)/e; where k is randomly selected so that it is perfectly divided, finally the d value is also printed.

Algorithm:Step1: startStep 2: declare the required variablesStep 3: accept any two prime numbers p & q.Step 4: check whether the accept numbers are prime or not. If not break.Step 5: calculate n=p*q;Step 6: calculate eq= (p-1)*(q-1).Step 7: for i =1 to eq do If gcd(eq,i)==1 then print I.Step 8: accept the selected e value from user.Step 9: compute d = ((i*eq)+1)/e by altering I value from 1 eq until it is perfectly divisible.Step 10: print the d value.Step 11: stop.

Algorithm for GCD (A,B)Step 1:if(b!=0) then return gcd(b,a%b);Step 2:else return aSTOP

Algorithm for PRIME (n)Step 1: for i=1 to n/2 step 1 doI f (n%i) ==0)

Then increment xStep2: if (x==1) then return 0 else return 1

STOP

Page 30: CN&CT_STAFF

Program:

#include<stdio.h>#include<math.h>main(){

int m,c,k,p,q,n,eq,e,I,d;int gcd(int eq,int e);int prime(int p);clrscr();printf(“enter any two prime numbers ex:3,5,7 etc \n”); /*enter prime numbers

*/scanf(“%d %d”,&p,&q);if(prime(p) || prime(q)) /*check for prime numbers */{

printf(“numbers are not prime”);exit(0);

}printf(“key generation\n”); /*calculation of n and euler tuotient */n=p*q;printf(“n is %d\n”,n);eq=(p-1)*(q-1);printf(“euler tuotient is %d\n”,eq);printf(“the e values are = \n”); /* to display all possible e values */for(i=1;i<eq;i++){

if(gcd(eq,i)==1)printf(“%d\t”i);

}printf(“\n choose any value ,corresponding d is displayed:”);scanf(“%d”,&e);for(i=1;i<=eq;i++){

d=((i*eq)+1)%e; /* to choose I values */if(d==0){

d=((i*eq)+1)/e;break;

}}printf(“d=%d”,d);getch();

}

Page 31: CN&CT_STAFF

int gcd(int a,int b) /*to compute gcd of a&b*/{

if (b!=0){

return gcd(b,a%b);}else {

return a;}

}

int prime(int n) /* function to check for prime number */{

int I,x=0;for(i=1;i<=n/2;i++){

if(n%i)==0)x++;

}if(x==1) /* if not prime returns 1 else 0 */

return 0;else

return 1;}

Page 32: CN&CT_STAFF

INPUT & OUTPUT:

1). Enter any two prime numbers ex: 3,5,7…etc 13. 7.Key generation.N is 91Euler tuotient is 72The e values are1 5 7 11 13 17 19 23 25 29 31 3537 41 43 47 49 53 55 59 61 65 67 71

Choose any e value, corresponding d is displayed. 5D=29.

2).Enter any two prime numbers ex: 3,5,7…etc 7. 11Key generation.N is 77Euler tuotient is 60The e values are1 5 7 11 13 17 19 23 25 29 31 3741 43 47 49 53

Choose any e value, corresponding d is displayed. 13D=37.

Observations:

1). When two prime num.s are given it gives all possible values for encryption key e.2). The e values range between 1 and eq-1.3). This works for all prime num.s.4). The n values are should be properly maintained.

Page 33: CN&CT_STAFF

Conclusion:

The program is error free.

Exp. No: 7(b).

Aim To implement RSA encryption.

Description:The program converts a given plain text into its encrypted form using RSA

algorithm. The program accepts the values of e , n for encryption process. The encryption of the plain text is done by formula c=me mod n. the above algorithm encryption function is implemented by the fast modulo expression evaluation.

Algorithm:Step 1: startStep 2: read input file and output file.Step 3: read ‘e’ value.Step 4: read ‘n’ value.Step 5: convert the ‘e’ value into binary form bin[ ]Step 6: encryption by d=me mod n implemented by fast modulo

exponentiation.Step 7: write encrypted text to the output file.Step 8: do 6, 7 until end of file.Step 9: write onto the screen.Step 10: stop.

Fast modulo exponentiation evaluator:int fast(int d, int k, int n){

d=1, m =2.for i=k to ‘0’ step -1 do

d= (d*d)%n;if (bin[i]==1) then

d=(d*m)%n.

Page 34: CN&CT_STAFF

return d; }

Program:

#include<stdio.h>#include<conio.h>main(){

FILE *f1,*f2;/* creating file pointers */char in[50],op[50];int I,k,b,bin[50],x;long int c,m,e,d,n,p,q;clrscr();printf(“RSA Encryption:”);printf(“Enter input file :”);fflush(stdin); /* clears the buffer */gets(in);printf(“Enter output file:”);fflush(stdin);gets(op);f1=fopen(in,”r”);/*oprns file in read mode */f2=fopen(op,”w”);/*opens file in write mode */printf(“Enter encryption key :”);scanf(“%ld”,&e);printf(“Enter any two prime num.s:”);scanf(“%ld”,&p);scanf(“%ld”,&q);n=p*q;i=-1;

Page 35: CN&CT_STAFF

b=e;while (b>0) /*calculating the binary value of key */{

bin[++i]=b%2;b=b/2;

}k=I;do /* calculating fast modular exponentiation */{

m=fgetc(f1);d=1;for(i=k;i>=0;i--){

d=(d*d)%n;if(bin[i]==1){

d=(d*m)%n;}

}fputc(c,f2);

}while(!feof(f1));fclose(f2);f2=fopen(op,”r”);printf(“The encrypted text is:”);while((x=fgetc(f2))!=EOF)printf(“%c”,x);getch();

}

INPUT & OUTPUT:

RSA encryption.

Enter input file path: z:\demo1.txt.Enter output file path : z:\demoout.txtEncryption key ‘e’=5.Give two prime num.s: P=13Q=7The final encrypted text isn>>6s”o>n;!!l151nr

RSA encryption

Page 36: CN&CT_STAFF

Enter input file path :z:\in.txtEnter output file path z:\out.txt

Encryption key e-=5

Give two prime numbers(p,q)P=13Q=7The final encrypted text is !));!!s;onr>>

Observations

1.the program is working for all capital letters2.the program works for e,n,values created3.the data encrypted can only be decrypted by decryption algorithm4.the length of plain text can vary

Conclusuion:The program is error free

Exp. No: 7(c).

Aim: To implement RSA decryption.

Description:The program converts a given cipher text into its decrypted form using RSA

algorithm. The program accepts the values of d, n for decryption process. The decryption of the cipher text is done by formula m=cd mod n. the above algorithm decryption function is implemented by the fast modulo expression evaluation.

Algorithm:Step 1: startStep 2: read input file and output file.Step 3: read ‘d’ value.Step 4: read ‘n’ value.Step 5: convert thev‘d’ value into binary form bin [ ]Step 6: decryption by m=cd mod n implemented by fast modulo

exponentiation.Step 7: write encrypted text to the output file.

Page 37: CN&CT_STAFF

Step 8: do 6, 7 until end of file.Step 9: write onto the screen.Step 10: stop.

Fast modulo exponentiation evaluator:int fast(int d, int k, int n){

d=1, m =2.for i=k to ‘0’ step -1 do

d= (d*d)%n;if (bin[i]==1) then

d=(d*m)%n.return d;

}

Program:

#include<stdio.h>#include<conio.h>main(){

FILE *f1,*f2;/* creating file pointers */char in[50],op[50];int I,k,b,bin[50],x;long int c,m,e,d,n,p,q;clrscr();printf(“RSA decryption:”);printf(“Enter input file :”);fflush(stdin); /* clears the buffer */gets(in);printf(“Enter output file:”);

Page 38: CN&CT_STAFF

fflush(stdin);gets(op);f1=fopen(in,”r”);/*oprns file in read mode */f2=fopen(op,”w”);/*opens file in write mode */printf(“Enter decryption key (d):”);scanf(“%ld”,&e);printf(“Enter any two prime num.s(p,q)”);scanf(“%ld”,&p);scanf(“%ld”,&q);n=p*q;i=-1;b=e;while(b>0) /*calculating the binary value of key */{

bin[++i]=b%2;b=b/2;

}k=I;do /* calculating fast modular exponentiation */{

m=fgetc(f1);d=1;for(i=k;i>=0;i--){

d=(d*d)%n;if(bin[i]==1){

d=(d*m)%n;}

}fputc(c,f2);

}while(!feof(f1));

fclose(f2);f2=fopen(op,”r”);printf(“The decrypted text is:”);while((x=fgetc(f2))!=EOF)printf(“%c”,x);getch();

}

INPUT & OUTPUT:RSA decryption.

Enter input file path: z:\demoout.txt.

Page 39: CN&CT_STAFF

Enter output file path : z:\dec.txt

decryption key ‘e’=29

Give two prime num.s: P=13Q=7The final decrypted text isRSA ENCRYPTION

RSA decryption

Enter input file path :z:\out.txtEnter output file path z:\out1.txt

decryption key e-=29

Give two prime numbers(p,q)P=13Q=7The final decrypted text is ENCRYPTION

Observations

1.the program is working for all capital letters2.the program works for e,n,values created3.the data encrypted can only be decrypted by decryption algorithm4.the length of plain text can vary

Conclusuion:The program is error free

Part - B

Page 40: CN&CT_STAFF

1. Library System

AIM : The student should take up the case study of Unified Library application which is mentioned in the theory, and Model it in different views i.e. Use case view, logical view, component view, Deployment view, Database design, forward and Reverse Engineering, and Generation of documentation ofthe project.

1. Problem Statement

The Library System is a web-based application used to automate a library. It

allows the librarian to maintain the information about books, magazines and CDs. It also

allows the librarian to maintain the information about its users. It provides the facilities

such as search for items, browse, checkout items, return items, make reservation, remove

reservation etc. to its users.

To borrow the items from the library, the users must register in the system. The

search option allows the users to search for any item in the library. If the user finds that

the required item is available in the library, he/she can checkout the item from the library.

If the item is currently not available in the library, the user can make reservation for the

item. When the item becomes available the respective user who made the reservation for

that item first is notified.

The reservation is canceled when the user checks out the item from the library or

through an explicit cancellation procedure.

The system allows the librarian to easily create, update, and delete information

about titles, borrowers, items and reservations in the system. The librarian is an employee

of the library who interacts with the borrowers whose work is supported by the system.

The Library System can run on popular web-browser platforms like Windows

Explorer, Netscape Navigator etc. It can be easily extended with new functionality.

Page 41: CN&CT_STAFF

2. Vision Document

A vision document describes the higher level requirements of the system specifying the

scope of the system.

The vision document for the Library System might be

It is a support system

The library lends books, magazines and CDs to borrowers who are registered in

the system

The Library System handles the purchases of new titles for the library

Popular titles are brought in multiple copies. Old books, magazines and CDs are

removed when they are out of date or in poor condition

The librarian is an employee of the library who interacts with the borrowers

whose work is supported by the system

A borrower can reserve a book, magazine or CD that is not currently available in

the library so that when it is returned or purchased by the library, the borrower is

notified

The reservation is canceled when the borrower checks out the book, magazine or

CD or through an explicit cancellation procedure

The librarian can easily create, update, and delete information about titles,

borrowers, items and reservations in the system

The system can run on popular web-browser platforms like Windows Explorer,

Netscape navigator etc.

The system is easy to extend with new functionality

Page 42: CN&CT_STAFF

3. Glossary

Key terms are denoted in italics within the use-case specifications.

Item - A tangible copy of a Title.

Title - The descriptive identifying information for a book or magazine. Includes

attributes like name and description.

Reservation - Whenever a borrower wishes to checkout an Item that is not available due

to previous checkout by a different borrower a request can be made (a reservation) that

locks the borrower in as the next person able to checkout the Item.

Actors

Borrower - Interactive actor who uses the library to search for Titles, make reservations,

checkout, and return Items.

Librarian - Interactive actor responsible for maintenance of the inventory, acting on

behalf of the borrowers, and general support of the library (non-automated as well).

Master Librarian - Interactive actor, themselves a Librarian, who is also responsible for

maintaining the set of librarians for the system.

Registered User - Any interactive user for whom the system maintains a system account.

This includes borrowers, librarians, and master librarians. Capabilities include basic

login, browsing and searching for Titles.

Page 43: CN&CT_STAFF

4. Supplementary Specification Document

4.1 Objective

The purpose of this document is to define the requirements of the Library system.

This document lists the requirements that are not readily captured in the use-cases

of the use-case model. The supplementary specification and use-case model

together capture a complete set of requirements of the system.

4.2 Scope

This supplementary specification defines the non-functional requirements of the

system such as reliability, performance, supportability, and security as well as

functional requirements that are common across a number of use-cases.

4.3 Reference

None

4.4 Common Functionalities

Multiple users must be able to perform their work concurrently

If the reserved item has been purchased or available, the borrower must be

notified

4.5 Usability

Page 44: CN&CT_STAFF

The desktop user interface shall be Widows NT or Windows 2000 compliant

4.6 Reliability

The system shall be 24 hours a day, 7 days a week and not more than 10% down

time

4.7 Performance

The system shall support up to 2000 simultaneous users against the central

database of any given data

The system must be able to complete 80% of all transactions within 5

minutes

4.8 Supportability

None

4.9 Security

The system must prevent borrowers from changing borrowers information,

items information, titles information, and librarians information

Only Librarian can modify borrowers information, items information, and

titles information

Only Master Librarian can modify librarians information

Page 45: CN&CT_STAFF

5. Use – Case Model

5.1 Actors

Actor is something external to the system and interacts with the system. Actor

may be a human being, device or some other software system.

For Library system, actors might be;

Librarian

Borrower

5.2 Use – Case

A use-case represents sequence of actions performed by the system that yields an

observable result of value for a particular actor. Use-case represents a functional

requirement of a system.

Page 46: CN&CT_STAFF

For Library system, we can find the following use-cases;

Login

Search

Browse

Check out item

Return item

Make reservation

Cancel reservation

Manage titles

Manage items

Manage borrowers

Manage librarians

5.3 Use - Case Diagram

Page 47: CN&CT_STAFF

Master Librarian Manage librarians

Check out item

Return item

Make reservation

Cancel Reservation

Borrower

Manage titles

Manage itemsLibrarian

Mange borrowers

Login

SearchRegistered User

Browse

Page 48: CN&CT_STAFF

5.4 Use – Case Descriptions

5.4.1 Use-Case Specification: Login

5.4.1.1 Description

A registered user can log in and, upon verification, can initiate subsequent actions.

5.4.1.2 Flow of Events

5.4.1.2.1 Basic Flow

1. Initiated when a registered user chooses to Login.

2. The system prompts for username and password.

3. The registered user enters a username and password and submits them.

4. The system authenticates the username and password combination.

5. The system authorizes the registered user according to the role(s) to which the

registered user has been assigned.

6. The system displays the main page and awaits subsequent action.

5.4.1.2.2 Alternative Flows

Invalid Username/Password

1. The system displays the Authentication Failed message.

Account Locked

1. The system displays the <appropriate message>.

Authentication Service Unavailable

1. The system displays a Service Unavailable message and does not

permit any further attempts to login.

5.4.1.3 Special Requirements

1. Up to three consecutive failed tries to login with invalid username/password

combination until locking an account.

Page 49: CN&CT_STAFF

2. Minimum password length is 8 characters, and must include a combination of

characters including at least one non-alphabetic character.

5.4.1.4 Preconditions

User has an account with the system

5.4.1.5 Post-conditions

5.4.1.5.1 Primary Success Post-condition

The user is considered authenticated and is viewing the main page from which

additional actions can be initiated.

5.4.1.5.2 Login Failure

If the Login fails as described in any of the alternatives above, an appropriate

message is displayed and the user is not considered authenticated.

5.4.1.6 Notes

1. So far we are not doing much with roles.

2. The “appropriate message” above is vague; we need to come up with how we

report this to the user.

3. We need to talk to security people about how reasonable it is to lock the user

account after some number of failed attempts. If we keep that rule, we’ll need an

Unlock Account use case.

Page 50: CN&CT_STAFF

5.4.2 Use-Case Specification: Browse

5.4.2.1 Description

A registered user can browse the contents of the library as a precursor to other actions.

5.4.3 Flow of Events

5.4.3.1 Basic Flow

1. Initiated when a registered user chooses to browse Titles.

2. The system responds by displaying all of the Titles in the system, along with

topical descriptions.

3. The registered user selects a Title for further information.

4. The system displays Title detail along with the Items and the available action

on each Item.

5.4.3.2 Alternative Flows

No records

1. The system displays message indicating no Titles are in the system.

5.4.4 Special Requirements

1. The Titles will be sorted alphabetically by the name.

Page 51: CN&CT_STAFF

5.4.5 Preconditions

The user has been authenticated.

5.4.6 Post-conditions

5.4.6.1 Primary Success Post-condition

The registered user is viewing a Title along with the related Items.

5.4.3 Use-Case Specification: Search

5.4.3.1 Description

A registered user can search the contents of the library as a precursor to other actions.

5.4.3.2 Flow of Events

5.4.3.2.1 Basic Flow

1. Initiated when a registered user chooses to perform a search of Titles.2. The system responds by providing the registered user a means to enter search

criteria.3. The registered user enters search criteria and initiates the query.4. The system determines results and displays the matching Titles, along with topical

descriptions.5. The registered user selects a Title for further information.6. The system displays Title detail along with the Items and the available action on

each Item.

5.4.3.2.2 Alternative Flows

No matches

1. The system displays message indicating no Titles in the system match this criteria.

5.4.3.3 Special Requirements

1. The search only searches based on the name of the Item, not description or any other field.

2. The system shall use the percent sign as a wildcard (in keeping with standard SQL idioms).

3. The results will be sorted alphabetically by the name.

Page 52: CN&CT_STAFF

5.4.3.4 Preconditions

The user has been authenticated.

5.4.3.5 Post-conditions

5.4.3.5.1 Primary Success Post-condition

The registered user is viewing a Title along with the related Items.

5.4.3.6 Notes

1. We might want to combine this with the Search use case. The combined use case

could be called Select Title and one of the original use cases could be the basic flow

and the other would be the alternative.

5.4.4 Use-Case Specification: Make Reservation

5.4.4.1 Description

This use-case starts when the user wants to make a reservation for an item

5.4.4.2 Flow of Events

5.4.4.2.1 Basic flow

1. The system prompts the borrower to enter the item information for which he

wants reservation

2. The borrower submits the item information

3. The system marks the item as reserved and associates the borrower with the

reservation

5.4.4.2.2 Alternative Flow

None

5.4.4.3 Special requirements

None

5.4.4.4 Pre-conditions

The borrower is viewing a particular title with an item that is not currently

available

Page 53: CN&CT_STAFF

5.4.4.5 Post-conditions

The item is marked as reserved and the reservation is saved in the database

5.4.4.6 Notes

1. So far there is no nice way to figure out what a borrower has reserved.

5.4.5 Use-Case Specification: Remove Reservation

5.4.5.1 Description

The borrower can remove an existing reservation for an item.

5.4.5.2 Flow of events

5.4.5.2.1 Basic Flow

1. The system prompts the borrower for the item information for which the

reservation is removed

2. The borrower enters the item information and submits

3. System marks the item as no longer reserved

5.4.5.2.2 Alternative Flows

None

5.4.5.3 Special requirements

None

Page 54: CN&CT_STAFF

5.4.5.4 Pre-conditions

The borrower is viewing a particular Title with an Item that is reserved by the borrower.

5.4.5.5 Post-conditions

The previously reserved Item is no longer reserved.

5.4.6 Use-Case Specification: Check out Item

5.4.6.1 Description

This use-case starts when the borrower wishes to check out an item from the library

5.4.6.2 Flow of Events

5.4.6.2.1 Basic Flow

1. The borrower performs a search for the desired titles

2. The system prompts the borrower to enter search criteria

3. The borrower specifies the search criteria and submits

4. The system locates matching titles and displays them to the borrower

5. The borrower selects titles to check out

6. The system displays the details of titles as well as whether or not there is an

available item to be checked out

Page 55: CN&CT_STAFF

7. The borrower confirms the check out

8. the system checks out the item

9. Steps 1-8 can be repeated as often as needed by the borrower

10. The borrower completes the check out

11. The system notifies the Librarian that the borrower has concluded the check out

item session and displays instructions for the borrower to collect the items

5.4.6.2.2 Alternative Flows

None

5.4.6.3 Special requirements

5.4.6.4 Pre-conditions

The borrower is viewing a particular Title with an Item that is currently available.

5.4.6.5 Post-conditions

The Item is demarked as checked out to the borrower.

5.4.7 Use-Case Specification: Return Item

5.4.7.1 Description

This use-case starts when the borrower wishes to return an item

5.4.7.2 Flow of Events

5.4.7.2.1 Basic Flow

1. The system prompts the borrower to enter the item information he wants to return

2. The borrower enters the item information and submits

3. The system marks the item as available

Page 56: CN&CT_STAFF

5.4.7.2.2 Alternative Flows

None

5.4.7.3 Special requirements

None

5.4.7.4 Pre-conditions

The borrower is viewing a particular Title with an Item that is checked out by the borrower.

5.4.7.5 Post-conditions

The Item is demarked as available.

5.4.7.6 Notes

A reasonable future enhancement would be to notify anyone with a reservation on the Item.

5.5 Activity Diagram

Page 57: CN&CT_STAFF

Login

Browse

Select title

Display status

Make reservation

Save reservation

Check out item

Notify librarian

Issue item

Take item

Page 58: CN&CT_STAFF

6. Design Model

6.1 Class Diagram

BookTitleauthor : String

getLendingTime()getAuthor()setAuthor()

MagazineTitlepublishingDate : Date

getLendingTime()getPublishingDate()setPublishingDate()

Titlename : Stringcost : FloatlendingTime : Integer

getName()setName()getCost()setCost()getLendingTime()setLendingTime()

LoancreationDate : Date

create()getCreationDate()setCreationDate()

ReservationcreationDate : DatereservationNumber

getStatus()getCreationDate()setCreationDate()getReservationNumber()

1

*

1

*

References

Itemtitle : Stringquantity

canLend()getTitle()getQuantity()setQuntity()

1

0..*

1

0..*Has

1

*

1

*

Has

Borrowername : Stringid : Integeraddress : String

canBorrow()canSearch()getId()setId()getName()setName()

*

1

*

1Borrows

*1 *1

Many

*

*

*

*

CheckOut

Page 59: CN&CT_STAFF

6.2 Sequence Diagram and Collaboration diagrams

6.2.1 Sequence Diagram for Login Use-case

s:User :LoginForm

enter userid and password

verify userid and password

6.2.2 Collaboration Diagram for Login Use-case

s:User :LoginForm

2: verify userid and password

1: enter userid and password

Page 60: CN&CT_STAFF

6.2.3 Sequence Diagram for Search Use-case

r:RegisteredUser :SearchForm :SearchController :Title

enter search criteria

searchsearch(criteria)

getMatching(criteria)

search(criteria)

gives results

gives results

select titledisplay results

get details

give detailsgive details

6.2.4 Collaboration Diagram for Search Use-case

Page 61: CN&CT_STAFF

r:RegisteredUser :SearchForm

:SearchController :Title

5: search(criteria)

1: enter search criteria2: search

8: select title

3: search(criteria)9: display results

4: getMatching(criteria)10: get details

6: gives results11: give details

7: gives results12: give details

6.2.5 Sequence Diagram for Browse Use-case

Page 62: CN&CT_STAFF

:RegisteredUser :BrowseForm :BrowseController :Title

browseborrow

getTitlelist

return title listreturn tiltie list

selectTitle

give detailsgive details(title)

getDetails(title)

return details

return details

6.2.6 Collaboration Diagram for Browse Use-case

:BrowseForm

:BrowseController :Title

:RegisteredUser

1: browse6: selectTitle

7: give details

2: borrow8: give details(title)

3: getTitlelist9: getDetails(title)

4: return title list10: return details

5: return tiltie list11: return details

Page 63: CN&CT_STAFF

6.2.7 Sequence Diagram for Make Reservation Use-case

:Borrower :ReservationForm

:ReservationController

:Reservation

enter details

make reservation

makeReservation(details)create

save

reservation ok

6.2.8 Collaboration Diagram for Make Reservation use-case

Page 64: CN&CT_STAFF

:Borrower :ReservationForm

:ReservationController

:Reservation

1: enter details2: make reservation

3: makeReservation(details)4: create5: save

6: reservation ok

6.2.9 Sequence Diagram for Remove Reservation Use-case

:Borrower :Reservation Form

:Reservation Controller

:Reservation

enter details

removeReservation

removeReservation

removeReservation

reservation removed

reservation removed

Page 65: CN&CT_STAFF

6.2.10 Collaboration Diagram for Remove Reservation Use-case

:Borrower :ReservationForm

:ReservationController

:Reservation

1: enter details2: removeReservation

3: removeReservation

4: removeReservation

5: reservation removed

6: reservation removed

6.2.11 Sequence Diagram for Check Out Item Use-case

Page 66: CN&CT_STAFF

:Tilte:Borrower :CheckOutItemForm

:CheckOutItem Controller

:Item :Librarian

enter criteria

search criteria

get matching criteria

search()

return details

return detailsselect details

get details (title)get details(title)

return details

return details

enter title

checkoutcheckout item

checkout item

set status

notify

Page 67: CN&CT_STAFF

6.2.12 Collaboration Diagram for CheckOut Item Use-case

:Borrower :CheckOutItemForm

:CheckOutItem Controller

:Tilte

:Item

:Librarian

1: enter criteria2: search()

7: select details12: enter title13: checkout

3: search criteria8: get details (title)14: checkout item

4: get matching criteria9: get details(title)15: checkout item

5: return details10: return details

6: return details11: return details

16: set status

17: notify

Page 68: CN&CT_STAFF

6.2.13 Sequence Diagram for Return Item Use-case

:Title:Borrower :ReturnItem Form

:ReturnItem Controller

:Item :Librarian

enter details

return itemreturn item

return itemset status

notify

return item accepted

return item accepted

6.2.14 Collaboration Diagram for Return Item Use-case

Page 69: CN&CT_STAFF

:Borrower

:ReturnItem Form

:ReturnItem Controller

:Title

:Item

:Librarian

1: enter details2: return item 3: return item

4: return item7: return item accepted

8: return item accepted

5: set status

6: notify

6.3 State chart Diagram for Title Class

Page 70: CN&CT_STAFF

Available

Reserved

removeReservation[ number of reservation>=1 ] / number of reservations--

makeReservation / number of reservations++

ReserveTitle / numberof reservations++removeReservation[ number of reservations>=1 ] / number of reservations--

Page 71: CN&CT_STAFF

7. Deployment Model

7.1 Component Diagram

Borrower.java

Library.java

Title.java Authenticate.java

Library.db

librarian.java

Item.java

IBorrower ILibrarian

Page 72: CN&CT_STAFF

7.2 Deployment Diagram

Client2

Client1

Library Server DBServer

Library.exe

Library.exe

Library.exe Library.db

Page 73: CN&CT_STAFF

Case Study: Restaurant System

1. Problem statement

The system is intended to support the day-to-day operations of a restaurant by

improving the processes of making reservations and allocating tables to customers.

The Restaurant system provides the facilities like

Record Booking

Cancel Booking

Record Arrival

Table Transfer

The new system can offer diners eat at the restaurant without making an advance

booking, if a free table is available. This is known as Walk-in.

The new system should display the same information as the existing booking

sheet and in same format, to make it easy for restaurant staff to transfer, to the new

system. When new bookings are recorded or changes made to existing bookings, the

display should be immediately updated, so that restaurant staff is working with the latest

information available.

Page 74: CN&CT_STAFF

2. Vision Document

The vision document describes the higher level requirements of the system, specifying

the scope of the system.

The vision document of restaurant system might be

It is a support system for restaurant

The restaurant makes bookings, cancel bookings, record arrivals and table

transfers of the customers.

The receptionist is the employee of the restaurant who interacts with the customer

whose work is supported by the system.

The customer rings up to make a booking there is a suitable table free at the

required day and time and the required day and time and the receptionist enters

customer’s name, phone no. and records booking.

When the customer arrives, his arrival is updated in the system and waiter attends

to them.

The customer can also cancel booking what he made or transfer the booking to

another day or time.

The receptionist can easily record , update and cancel the information about the

bookings and customers

The customers eat in restaurants even with out any reservations or bookings called

Walk-in.

Page 75: CN&CT_STAFF

3. Glossary

This document is used to define terminology specific to the problem domain,

explaining terms which may be unfamiliar to the reader. This document can be used as

informal data dictionary capturing data definitions, key terms.

Booking:

An assignment of a table to a party of dinners for a meal

Covers:

The number of diners that a booking is made for

Reservation:

An advanced booking for a table at a particular time

Places:

The number of diners that can be seated at a particular table

Walk-In:

A booking that is not made in advance.

Actors:

Customer:

The person making a reservation

Page 76: CN&CT_STAFF

Diner:

A person eating at the restaurant

4. Supplementary Specification Document

4.1 Objective

The purpose of this document is to define the requirements of the restaurant system. The

supplementary specification lists the requirements those are not readily captured in the

use cases of the use case model. The supplementary specification and the use case model

together capture a complete set of requirements of the system.

4.2 Scope

This specification defines the non-functional requirements of the system such as

reliability, usability, performance, supportability and security. As well as functional

requirements that are common across a no. of use cases.

4.3 References

None

4.4 Common Functionalities

Multiple customers can be able to visit a restaurant.

Customers who have recorded booking must be notified.

4.5 Usability

The desktop user interface shall be Windows NT and Windows 2000 complaint.

4.6 Reliability

Page 77: CN&CT_STAFF

The system shall be available 24 hrs a day, 7 day a week to no more than 10% downtime.

4.7 Performance

The system shall support up to 1000 simultaneous users against the central data base of

any given time.

4.8 Supportability

None

4.9 Security

The system must prevent customers from changing information like record

booking, date and timings of reservations.

Only receptionist can modify customer’s information of record booking,

updates and cancel booking.

Only proprietor can modify the receptionist information.

Page 78: CN&CT_STAFF

5. Use - Case Model

5.1 Actors

Actor is something external and interacts with the system. Actor may be a human being

or some other software system.

For restaurant system

Receptionist

5.2 Use cases

Use cases represent the functional requirements:

Record Booking

Cancel Booking

Table Transfer

Record Arrival

Record Walk-in

Display Bookings

Page 79: CN&CT_STAFF

5.3 Use Case Diagram

Page 80: CN&CT_STAFF

<<extend>>

Receptionist

Staff

Record Booking

Record Arrival

Record Walk-in

<<include>>

Cancel Booking

Display Bookings

<<include>>

<<include>>

<<include>>

Head Waiter

Table Transfer

<<include>>

Page 81: CN&CT_STAFF

5.4 Use-case Specifications

5.4.1 Use-Case Specification: Record Booking

5.4.1.1 Description

This use case starts when the receptionist want to record the bookings the customer have made.

5.4.1.2 Flow of Events

5.4.1.2.1 Basic Flow

1. The bookings are recorded into the restaurant database.

2. The receptionist enters the date of the requested reservation.

3. The system displays the bookings for that date.

4. There is a suitable table available; the receptionist enters the customers name and phone number the time of booking, the number of covers and the table.

5. The system records and displays new booking.

5.4.1.2.2 Alternate Flow

1. The receptionist enters the date of the requested reservation.

2. The system displays the bookings for that date.

3. No suitable table is available and the use-case terminates.

5.4.1.3 Precondition

The customer wants to reserve the table in restaurant on particular date.

5.4.1.4 Post condition

The customer successfully reserves the table on the required date.

Page 82: CN&CT_STAFF

5.4.2 Use-Case Specification: Record Arrival

5.4.2.1 Description

This use case starts when customer arrived at restaurant.

5.4.2.2 Flow of Events

5.4.2.1.1 Basic Flow

1. The headwaiter enters the current date.

2. The system displays the booking for the date.

3. The headwaiter confirms arrival for the selected booking.

4. The system records this and updates the display, marking the customer as having arrived.

5.4.2.1.2 Alternate Flow

1. The headwaiter enters the current date.

2. The system displays the bookings for that date.

3. There are no bookings recorded on the system for the customer, so the head waiter creates a walk-in booking, by entering the time of booking, number of covers and the table number.

4. The system records and displays the new bookings.

5.4.2.3 Precondition

The customer must reserve the table.

5.4.2.4 Post condition

The arrival of the customer is updated.

Page 83: CN&CT_STAFF

5.4.3 Use-Case Specification: Display Booking

5.4.3.1 Description

This use case starts when the customer wants to see the bookings on that date.

5.4.3.2 Flow of Events

5.4.3.2.1 Basic Flow

1. The user enters a date.

2. The system displays the bookings for that date.

5.4.3.2.2 Alternate Flow

1. System displays no bookings on that date.

5.4.3.3 Pre-condition

User should be the member of restaurant and must enter the date.

5.4.3.4 Post condition

System displays the bookings on the entered date.

Page 84: CN&CT_STAFF

5.4.4 Use-Case Specification: Cancel Booking

5.4.4.1 Description

This use case starts when the customer wants to cancel the booking he has made.

5.4.4.2 Flow of Events

5.4.4.2.1 Basic Flow

1. The receptionist selects required booking.

2. The receptionist cancels the booking.

3. The system asks the receptionist to confirm the cancellation.

4. The receptionist answers ‘yes’, so the system records the cancellation and

updates display.

5.4.4.2.2 Alternate Flow

1. The system displays no reservations of customers.

5.4.4.3 Precondition

The customer must have already booked the table.

5.4.4.4 Post condition

The booking of the customer gets canceled.

Page 85: CN&CT_STAFF

5.4.5 Use-case Specification: Table Transfer

5.4.5.1 Description

This use case specification starts when head waiter wants to transfer the booked table.

5.4.5.2 Flow Of Events

5.4.5.2.1 Basic Flow

1. The head waiter selects required booking.

2. The head waiter changes the table allocation of the booking.

3. The system records the alteration and updates display.

5.4.5.2.2 Alternative Flows

1. When it is not possible move a booking to a table that is already occupied

5.4.5.3 Precondition

The table is already booked by another person.

Page 86: CN&CT_STAFF

5.4.5.4 Post condition

The table gets transferred.

5.4.6 Use-case Specification: Record Walk In

5.4.6.1 Description

This use case starts when some one arrives to eat in the restaurant with out reservation.

5.4.6.2 Flow Of events

5.4.6.2.1 Basic Flow

1. The headwaiter performs display bookings use case.

2. The head waiter enters the time, the number of covers and table allocated to

customer.

3. The system records and displays new booking.

5.4.6.3 Alternative Flow

No table is available as free.

5.4.6.4 Pre-conditions

Page 87: CN&CT_STAFF

The person should not reserve the table in advance.

5.4.6.5 Post conditions

The system records walk in.

5.5 Activity Diagram

Page 88: CN&CT_STAFF

Record booking

RecordWalkin

Make Reservation

Enters Date

Display Details on the date

Display Booking

Record Arrival

reservation

[ available ]

[ not available ]

free table

[ available ]

[ not avalable ]

Page 89: CN&CT_STAFF

6. Design Model

6.1 Class Diagram

WalkIn

{Must be one of the current bookings.}

{Bookings for the same table must not overlap.}

current

selected

MakesReservation

arrivalTime : Float

setArrivalTime()

BookingSystem

date : Date

cancel()display()makeReservation()recordArrival()selectBooking()updateDisplay()

Booking

covers : Integerdate : Datetime : Float

getDate()getDetails()setArrivalTime()setTable()

**

**

Table

number : Integerplaces : String

1* 1*

Customer

name : StringphoneNumber : Integer

1* 1*

Restaurant

getBookings()getCustomer()getTable()makeReservation()

11

**

**

**

Page 90: CN&CT_STAFF

6.2 Sequence and Collaboration Diagrams

6.2.1 Sequence Diagram for Record Booking Use-case

:Receptionist :Booking System

:Restaurent c:Customer t:Table :Reservation

makeReservation(details)makeReservation(details)

getTable(tno)

return t

c:=getCustomer(name e,phoneno)

Reservation(date,t,c)

reservation ok

reservation ok

updateDisplay()

updateDisplay()

Page 91: CN&CT_STAFF

6.2.2 Collaboration Diagram for Record Booking Use-case

:Receptionist :Booking System

:Restaurent

c:Customer t:Table :Reservation

9: updateDisplay()

1: makeReservation(details)

10: updateDisplay()

2: makeReservation(details)

8: reservation ok

5: c:=getCustomer(name e,phoneno)

3: getTable(tno)

4: return t 6: Reservation(date,t,c)

7: reservation ok

Page 92: CN&CT_STAFF

6.2.3 Sequence Diagram for Display Booking Use-case

:staff :Booking System

:Restaurent :Booking

display()getBookings(date)

getDate()

return datereturn bookings

updateDisplay()

updateDisplay()

6.2.4 Collaboration Diagram for Display Booking Use-case

Page 93: CN&CT_STAFF

:staff :Booking System

:Restaurent :Booking

6: updateDisplay()

1: display()

7: updateDisplay()

2: getBookings(date)

5: return bookings

3: getDate()

4: return date

6.2.5 Sequence Diagram for Cancel booking Use-case

Page 94: CN&CT_STAFF

:Staff :BookingSystem

Current: Booking

Selected: Booking

selectBooking(id)getDetails()

returnDetails()

cancel()

confirm()

return 'yes'destroy

updateDisplay()

updateDisplay()

6.2.6 Collaboration Diagram for Cancel booking Use-case

:Staff :BookingSystem

Selected: Booking

Current: Booking

8: updateDisplay()

1: selectBooking(id)4: cancel()

6: return 'yes'

3: returnDetails()5: confirm()

9: updateDisplay()

2: getDetails()

7: destroy

Page 95: CN&CT_STAFF

6.2.7 Sequence Diagram for Record Arrival Use-case

:Staff :Booking System

current:Booking

selected: Reservation

selectBooking(id)getDetails()

returnDetails()returnDetails()

recordArrival()setArrivalTime(now)

updateDisplay()

updateDisplay()

6.2.8 Collaboration Diagram for Record Arrival Use-case

Page 96: CN&CT_STAFF

:Staff :Booking System

current:Booking selected: Reservation

7: updateDisplay()

1: selectBooking(id)5: recordArrival()

4: returnDetails()8: updateDisplay()

2: getDetails()

3: returnDetails()6: setArrivalTime(now)

6.2.9 Sequence Diagram for Table Transfer Use-case

Page 97: CN&CT_STAFF

:BookingSystem

:HeadWaiter Current: Booking

selected: Booking

select booking idgetDetails()

return details

makeTableTransfer(id)update booking

update display

updateDisplay()

6.2.10 Collaboration Diagram for Table Transfer Use-case

:HeadWaiter :BookingSystem

Current: Booking selected: Booking

6: update display

1: select booking id4: makeTableTransfer(id)

3: return details7: updateDisplay()

2: getDetails()5: update booking

Page 98: CN&CT_STAFF

6.2.11 Sequence Diagram for Record Walk-in Use-case

:Receptionist :Booking System

:Restaurent :Reservation

makeReservation(details)makeReservation(details)

reserve table Walk-in

reservation ok

reservation ok

updateDisplay()

updateDisplay()

6.2.12 Collaboration Diagram for Record Walk-in Use-case

Page 99: CN&CT_STAFF

:Receptionist :Booking System

:Restaurent :Reservation

6: updateDisplay()

1: makeReservation(details)

7: updateDisplay()

2: makeReservation(details)

5: reservation ok

3: reserve table Walk-in

4: reservation ok

6.3 State chart Diagrams

6.3.1 State chart diagram for Booking Class

NotSelected Selected

SelectBooking[ no booking ]

selectBooking[ booking found ]

selectBooking[ booking found ]

/select new booking

/select new booking

Page 100: CN&CT_STAFF

6.3.1 State chart diagram for Reservation Class

Booked Seated

setTable

cancel

setArrivalTime

setTable

7. Deployment Model

7.1 Component Diagram

Page 101: CN&CT_STAFF

StaffUI.java

BookingSystem.java

BookingObserver.java

Restaurant.java Booking.java

Customer.javaTable.java

7.2 Deployment Diagram

Page 102: CN&CT_STAFF

ClientCustomer.exe

<<process>>

ClientReceptionist.exe

<<process>>

Booking SystemReservation.exe

<<process>>

DB Server Restaurant.db

<<process>>

Page 103: CN&CT_STAFF

Viva – Voce Questions

1. How many structural and behavioral diagrams are there in UML?Ans; 4- Structural and 5-behavioral diagrams

2. What is used to create new building blocks in UML?Ans: stereotypes

3. A use case is rendered asAns: As an ellipse

4. The names of use cases are generally given asAns: Verb phases

5. Actors are connected to use cases only byAns: Association relationship

6. The behavior of a use case is specified byAns: Flow of events

7. Extension scenarios are also called asAns: Alternative Flows

8. What diagram is used to model the requirements of a systemAns: Use Case Diagram

9. In UML signals are modeled asAns: Stereo Typed classes

10. What diagram is used to model the vocabulary of a systemAns: Class diagram

11. Internal event occurs whenAns: A method is invoked via a message

12. Graphically, a component is rendered asAns: A Rectangle with tabs

13. What diagram is used to model a physical databaseAns: Component Diagram

14. What is used to specify the properties of UML building blocks?Ans: Tagged values

15. What diagram is used to model logical database schemaAns: Class diagram

Page 104: CN&CT_STAFF

2.AIM: Student has to take up another case study of his/her own interest and do the same what ever mentioned in first problem. Some of the ideas regarding case studies are given in reference books which were mentioned in theory syllabus can be referred for some idea.

ADDITIONAL EXPERIMENTS

1(a) AIM: BIT DE-STUFF

Implement the data link layer framing method of de-stuffing

DESCRIPTION:

In bit stuffing technique each frame begins and ends with a special bit pattern, 01111110 called a flag byte. When ever the sender’s data link layer encounters five consecutive ones in the data, it automatically stuffs a 0 bit into the outgoing bit stream. This bit stuffing in which DLE is stuffed into the outgoing character stream before DLE in the data. When the receiver sees five consecutive incoming 1 bits followed by a 0 bit, it automatically de-stuffs the ‘0’ bit. Like character stuffing, bit stuffing is also completely transparent to the network layer in both the computers.

ALGORITHM:

Step 1: Read the input stream

Step 2: Scan the stuffed string from left to right

Step 3: IF there is a’0’ after 5 1’s

Go to step 5

Step 4: Place the scanned bit in the de-stuffed string Go to step 6

Page 105: CN&CT_STAFF

Step 5: De-stuff the ‘0’ bit from the stuffed string

Step 6: Repeat the process until the end of the stuffed string

Step7: Print the de-stuffed string

Step 8: Stop

Program:

import java.io.*;import javax.swing.*;import java.lang.String.*;class bitdstuff{

public static void main(String args[]){

int i,l=0;/*Reading the flag value from user*/String f=JOptionPane.showInputDialog("enter the flag string: ");/*checking the number of 1’s in the flag*/for(i=0;i<f.length();i++){

if(f.charAt(i)=='1'){

l++;}

}int j=0;JOptionPane.showMessageDialog(null,"l= "+l);/*Reading stuffed data from the user*/String s1=JOptionPane.showInputDialog("enter the data: ");for(i=s1.length()-f.length();i<s1.length();i++){

if(s1.charAt(i)!=f.charAt(j)){

JOptionPane.showMessageDialog(null,"wronginput");System.exit(0);

}j++;

}

String s2=" ";int c=0;/*Performing De-Stuffing operation*/for(i=f.length();i<s1.length()-f.length();i++)

Page 106: CN&CT_STAFF

{if(c==l-1){

c=0;i++;

}

if(s1.charAt(i)=='1'){

c++;s2+=s1.charAt(i);

}else{

c=0;s2+=s1.charAt(i);

}}/*Printing the original message*/JOptionPane.showMessageDialog(null," stuffed message is" +s1+

"\noriginal message is "+s2);}

}

Output:

Page 107: CN&CT_STAFF

Viva Questions:

1. What is Bit De-Stuffing?Ans.In Bit De-Stuffing the receiver de-stuffs the receives stuffed data and gets the original data.

2. How is data de-stuffed?Ans. First the flags on both the ends of the stuffed data are removed. After that stuffed bits are removed and finally we yield original data.

3. What is charAt()?Ans. The charAt() method returns the character at a specified position

4. What is length()?Ans. The length property returns the number of characters in a string.

1(b) AIM: CHARACTER DE-STUFF

To receive the transmitted stuffed characters through the data link layer and de-stuff it.

DESCRIPTION:

In this method of character stuffing each frame starts with the ASCII characters sequence DLE STX and end with the sequence DLE STX ( DLE is Data Link Escape

Page 108: CN&CT_STAFF

and STX is Start of Text and ETX is End of Text) which indicate the beginning and end of text. It may easily happen that the characters DLE occur in the data which will interfere with The framing In order to solve the problem sender’s data link layer inserts an ASCII DLE Character just before each accidental “DLE” character in the data. The data link layer on the receiving end removes the DLE before the data are given to the network layer. This is called character stuffing.

The data link layer on the receiver side will remove the DLE character of the stuffed string. This process of removing is called De-stuffing.

ALGORITHM:

Step 1: Scan the stuffed string for flag

Step 2: IF flag found Go to step 3 Else Go to step 4

Step 3: Remove flag from stuff data

Step 4: Place the characters to de-stuffed data

Step 5: IF (stuffed string !=’\0’) Go to step2

Step 6: Write stuffed and de-stuffed string

Step 7: Stop

Program:

import java.io.*;import javax.swing.*;import java.lang.String.*;class chardstuff{

public static void main(String args[]){

Page 109: CN&CT_STAFF

int n,i,j,b=0;char p,q,r;String c=" ";String f=" ";String l=" ";/*Reading the encrypted data and flag value from the user*/String s1=JOptionPane.showInputDialog("enter the encrypted string: ");String s2=JOptionPane.showInputDialog("enter the flag string: ");try{

/*Extracting the flag value and data from encrypted string*/for(j=0;j<3;j++){

f+=s1.charAt(j);}for(j=s1.length()-3;j<s1.length();j++){

l+=s1.charAt(j);}/*Performing the character de stuffing operation*/if(f.equals(l)){

for(i=3;i<s1.length()-3;i++){

/*Removing the flag and stuffed data*/p=s2.charAt(0);if(s1.charAt(i)==p||s1.charAt(i)==(p=32)||s1.charAt(i)==(p+=64)){

c+=s1.charAt(i);i++;q=s2.charAt(1);if(s1.charAt(i)==q||s1.charAt(i)==(q

=32)||s1.charAt(i)==(q+=64)){

c+=s1.charAt(i);i++;r=s2.charAt(2);if(s1.charAt(i)==r||s1.charAt(i)==(r

=32)||s1.charAt(i)==(r+=64))

{c+=s1.charAt(i);i+=3;

}else

Page 110: CN&CT_STAFF

{c+=s1.charAt(i);

}}else{

c+=s1.charAt(i);}

}else{

c+=s1.charAt(i);}

}/*Printing the destuffed string*/JOptionPane.showMessageDialog(null,"destuffed String

is:"+c);}else{

JOptionPane.showMessageDialog(null,"wrong input");}System.exit(0);

}catch(Exception e){}}

}

Output:

Page 111: CN&CT_STAFF

Viva:-

1) What is Character Destuffing?Ans) Character Destuffing is the process of deleting the DLE STX and DLE ETX at the starting and ending of the frame.

2) In which layer Character Destuffing is performed?Ans) Data Link Layer at the receiver side.

3) If the data received is DLESTXabcddledleDLEETX then what is the destuffed output?Ans) abcdle

4) What is the need of Character Stuffing and Destuffing?Ans) It is used to specify the starting and ending of a frame to the receiver.

Page 112: CN&CT_STAFF

Exp No: 2(a)Aim: Understanding the buffer overflow using strcpy()

Description: ATTACKERS CAN TAKE ADVANTAGE OF VULNERABILITIES

RESULTING FROM SLOPPY CODING, THAT LETS THEM ALTER NEARBY MEMORY LOCATIONS. EXAMPLES OF THIS ISSUE ARE EXPLAINED AS FOLLOWS .

In computer security and programming a buffer overflow or a buffer overrun, is an anomalous condition where a process attempts to store data beyond the boundaries of a fixed length buffer. The result is that the extra data over writes adjacent memory locations. The over written data may include other buffers, variables and program flow data and may result in erratic program behavior, a memory access exception, program termination (a crash) causing a breach of system security.

The programming languages which are commonly associated with buffer overflows are c and c++, since they provide no built in protection against accessing or overwriting data in any part of memory and do not check data written to an array is written the boundaries of that array.

To illustrate this we try to use the example of strcpy() and stack . this program would show how can a buffer overflow happen.Algorithm:

Step 1: startStep 2: take two string variables one for source and the other for destinationStep 3: read the source string and compute the length of itStep 4: read the length of the destination string, where the source is to be copiedStep 5: if the length of the source string is greater than the destination string the buffer overflowsStep 6: if the length is within the limits if the destination string then while using strcpy(), we can copy the source stringStep 7: stop

Page 113: CN&CT_STAFF

Input/Output:1. Enter the source string: gec Enter the length of destination string:4 gec2. Enter the source string: gec Enter the length of destination string:2 buffer overflow3. Enter the source string: gec246 Enter the length of destination string:6 gec246

Observations :1. every time we perform a strcpy() there is a check done to ensure the buffer size2. irrespective of characters or integers it should work, to insure no buffer overrunConclusion:

program is error free

Page 114: CN&CT_STAFF

Exp No: 2(b)Aim: To implement a program which makes us understand buffer overflow?

Description:Buffer overflow concept can also be explained using the traditional concept of

one linear data structures like stack. Stack is a collection of data elements which performs insertion, deletion in a LIFO (Last In First Out) order. Usually these insertion , deletion operations are known as push and pop. The concept of buffer overflow is explained when the stack reaches its maximum storage capacity. Thus resulting in the hazard.

Algorithm:Step 1: startStep 2: create an array of some maximum size and create a pointer variable which points to the index of the starting element.Step 3: when we insert an element the value is stored using the pointer variable into the stack and prior to this operation pointer points to the next location.Step 4: a check on pointer is maintained to ensure buffer overflow if the pointer value is greater than size of stack then buffer overflows.Step 5: similar to step 3 the value is deleted from the stack when the pointer is decrement.Step 6: display the elements of the stack which decrementing the value of the value of pointerStep 7: stop

Input/Output:1) Enter your choice

1)push2)pop3)display4)exit

1Enter the elements to be inserted 2Insertion successfulEnter your choice 1Enter the elements to be inserted 4Insertion successfulEnter your choice 1Enter the elements to be inserted 6Insertion successfulEnter your choice 1Buffer overflow!!Enter your choice

Page 115: CN&CT_STAFF

32 4 6 are the elements2.) Enter your choice

1)push2)pop3)display4)exit1

Enter the elements to be inserted ‘a’Insertion successfulEnter your choice 1Enter the elements to be inserted 3Incorrect inputEnter your choice 2Element ‘a’ deletedEnter your choice2Buffer overflow!!

Observation:1. a check is performed in push() operation to ensure buffer overflow2. a check is performed in pop() operation to ensure underflow3. stack could take only identical data values either only integers or char’s etcconclusion:program is error free

Exp No: 3(a)Aim: To implement a program to explain format string vulnerabilityDescription:

Format string vulnerabilies are the result of programmers allowing externally supplied unsanitized data in the format string argument. The best solution to format string vulnerabilities is prevention.

There are three basic goals an attacker can accomplish by exploiting format string vulnerabilities. First the attacker can cause a process to fail due to an invalid memory access. This can result in a denial of service. Second, attackers can read process memory if the formatted string is output. Finally memory can be over written by attackers possibly leading to executing of instructions. The solution to format string vulnerability involves attempting to count the number of arguments passed to a printf() function compared to % tokens in the format string.Algorithm:

Input: dOutput : tStep 1: startStep 2: read a double value into d

Page 116: CN&CT_STAFF

Step 3: assign the double value d to a integer type variable tStep 4: print the integer value tStep 5: stop

Observations: When user is trying to print the double value using the (%d) integer specifier,

only the integer part will be printed. The precision value is lost this is format string vulnerability.Input & Output:1. Enter double value 22.765

22 is the value which results format string vulnerability.2. Enter double value 33.05

33 is the value which results format string vulnerability3. Enter double value 44.723

44 is the value which results format string vulnerabilityConclusion:

The format string vulnerability is shown clearly here

Page 117: CN&CT_STAFF

Exp No: 3(b)Aim: To implement a program to explain format string vulnerabilities Description:

The use of wrappers for printf() style functions, often for logging and error reporting functions, is very common. One of the most common causes of format string vulnerabilities is improper calling of the syslog() function on UNIX systems. Example of string vulnerability is as below. Similar to the strcpy function is strcat. A common programming error is the use of the strcat function without first checking the size of the array. The mistake is usually made by never programmers, and is due to unfamiliarity with the c library string processing functions. Some times this mistake is due to programmer’s laziness, neglecting to in include a format string argument for the string (i.e. %s). This reason is often the underlying cause of many different types of security vulnerabilities in software.Algorithm:

Input: s,lOutput; s,lStep 1: startStep 2: read the string through gets () function into sStep 3: print the string by using string functionStep 4: compare the read the string ito l through scanf functionStep 5: print the string by using printf functionStep 6: compare the two strings s,l and print ‘equal’ if they are equal else print ‘not equal’Step 7: stop

Observations:1. Two same strings are read in two ways. One string is read through gets() function

and the other string is read through scanf() function2. Gets function reads the string until end line character occurs where as scanf()

reads the string until end line character or space. So, even the strings are same it shows not equal which is format string vulnerability.

Input & Output:1. enter the string to read through gets welcome to gec

welcome to gecenter the string to read through scanf

welcome to gecwelcome

not equal due to format string vulnerability2. enter the string to read through gets prasad

prasadenter the string to read through scanf

Prasadprasad

equal3. enter the string to read through gets

Page 118: CN&CT_STAFF

India is our countryIndia is our country

enter the string to read through scanfIndia is our countryindia

not equal due to format string vulnerabilityConclusion:

The format string vulnerability is shown successfully

Page 119: CN&CT_STAFF