0% found this document useful (0 votes)
24 views14 pages

CNS LabPrograms PDF

The document contains code for several algorithms: 1. A Leaky Bucket algorithm that simulates a bucket with a maximum capacity and output rate, rejecting packets that exceed the capacity. 2. A Bellman-Ford algorithm that finds the shortest paths from a source node to all other nodes in a graph, checking for negative cycles. 3. A Dijkstra's algorithm implementation that finds the shortest path between a source node and all other nodes in a graph. 4. An RSA encryption algorithm that encrypts and decrypts messages using the RSA public-key cryptosystem. 5. A DES encryption algorithm that encrypts and decrypts strings using the DES symmetric-key algorithm. 6. An

Uploaded by

Bunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views14 pages

CNS LabPrograms PDF

The document contains code for several algorithms: 1. A Leaky Bucket algorithm that simulates a bucket with a maximum capacity and output rate, rejecting packets that exceed the capacity. 2. A Bellman-Ford algorithm that finds the shortest paths from a source node to all other nodes in a graph, checking for negative cycles. 3. A Dijkstra's algorithm implementation that finds the shortest path between a source node and all other nodes in a graph. 4. An RSA encryption algorithm that encrypts and decrypts messages using the RSA public-key cryptosystem. 5. A DES encryption algorithm that encrypts and decrypts strings using the DES symmetric-key algorithm. 6. An

Uploaded by

Bunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

1 Leaky Bucket

import java.util.*;
public class LeakyBucket {
public final static int max=25;
static int min(int a,int b)
{
if(a<b)
return a;
return b;
}

public static void main(String[] args) {


Scanner scan= new Scanner(System.in);
int cap,optr,ch,count,nsec,i=0;
int inp[]=new int[max];
System.out.println("Leaky bucket algo");
System.out.println("Enter the bucket size");
cap=scan.nextInt();
System.out.println("enter the output rate");
optr=scan.nextInt();
do{
System.out.println("enter the packet received at "+(i+1)+"Seconds");
inp[i]=scan.nextInt();
i++;
System.out.println("\n enter 1 to send more packets else 0 to quit");
ch= scan.nextInt();
}while(ch!=0);
nsec=i;
System.out.println("n(seconds):(pktreceived):(pktinbucket):(packsent):(packleft)");
count=0;
for(i=0;i<nsec;i++){
count+=inp[i];
if(count>cap){
System.out.println("accept incoming packets for the bucket");
System.out.println("the excess packet rejected from the bucket at"+(i+1)+"sec
is "+(count-cap));
count=cap;
System.out.println();
}
System.out.println("c(c"+(i+1)+"):");
System.out.println("\t\t("+inp[i]+"):");
System.out.println("\t\t("+count+"):");
System.out.println("\t\t("+min(count,optr)+"):");
count= count-min(count,optr);
System.out.println("("+count+"):");
}

}
2 Bellmanford Algorithm

import java.util.*;
import java.math.*;
public class BellanFord {
static Scanner scan=new Scanner(System.in);
static int cost[][],prevd[],dist[],n;
static void bf() {
for(int k=0;k<n-1;k++) {
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(cost[j][i]!=999 && prevd[j]!=999 &&
dist[i]>prevd[j]+cost[j][i])
dist[i]=prevd[j]+cost[j][i];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(cost[j][i]!=999 && prevd[j]!=999 &&
dist[i]>prevd[j]+cost[j][i])
System.out.println("neagtive cycles");
}
}
public static void main(String[] args) {
System.out.println("Enter the of vertices");
n=scan.nextInt();
cost=new int[n][n];
dist=new int[n];
prevd=new int[n];
System.out.println("Enter cost matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++) {
cost[i][j]= scan.nextInt();
if(cost[i][j]==0 && i!=j)

cost[i][j]=999;
}
System.out.println("Enter the source");
int s = scan.nextInt();
for(int l=0;l<n;l++) {
dist[l]=prevd[l]=cost[s][l];
}
bf();
System.out.println("the distances are");
for(int k=0;k<n;k++) {
System.out.println(s+" to "+ k +":"+dist[k]);
}

}
3 Dijkstra’s Program
import java.util.*;
public class Dijkstra
{
public int distance[] = new int[10];
public int cost[][] = new int[10][10];
public void calc(int n,int s)
{
int flag[] = new int[n+1];
int i,minpos=1,k,c,minimum;
for(i=1;i<=n;i++)
{
flag[i]=0;
this.distance[i]=this.cost[s][i];
}
c=2;
while(c<=n)
{
minimum=99;
for(k=1;k<=n;k++)
{
if(this.distance[k]<minimum && flag[k]!=1)
{
minimum=this.distance[i];
minpos=k;
}
}
flag[minpos]=1;
c++;for(k=1;k<=n;k++)
{
if(this.distance[minpos]+this.cost[minpos][k] < this.distance[k] && flag[k]!=1 )
this.distance[k]=this.distance[minpos]+this.cost[minpos][k];
}
}
}
public static void main(String args[])
{
int nodes,source,i,j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the Number of Nodes \n");
nodes = in.nextInt();
Dijkstra d = new Dijkstra();
System.out.println("Enter the Cost Matrix Weights: \n");
for(i=1;i<=nodes;i++)
for(j=1;j<=nodes;j++)
{
d.cost[i][j]=in.nextInt();
if(d.cost[i][j]==0)
d.cost[i][j]=999;
}
System.out.println("Enter the Source Vertex :\n");
source=in.nextInt();
d.calc(nodes,source);
System.out.println("The Shortest Path from Source \t"+source+"\t to all other vertices
are : \n");
for(i=1;i<=nodes;i++)
if(i!=source)
System.out.println("source :"+source+"\t destination :"+i+"\t MinCost is :"+d.distance[i]
+"\t");
}
}

4 RSA
import java.util.*;
import java.math.*;
public class Rsa {
static Scanner scan = new Scanner(System.in);
static int p,q,n,z,e,d,ed[],dd[],num[];
static BigInteger temp;
static String msg;
static int gcd(int a, int b) {
if(a==0)
return b;
return gcd(b%a,a);
}
static void rsaAlg(String msg) {
p=7;
q=11;
n=p*q;
z=(p-1)*(q-1);
for(int i=2;i<z;i++)
if(gcd(i,z)==1) {
e=i;
break;
}
for(int i=2;i<z;i++)
if((e*i)%z==1) {
d=i;
break;
}
System.out.println("p="+p+ "q="+q+ "\nn="+n+ "z="+z+
"\ne=" +e+"d=" +d);
num= new int[msg.length()];
ed= new int[msg.length()];
dd= new int[msg.length()];
for(int i=0;i<msg.length();i++)
num[i]=msg.charAt(i)-'a'+1;
for(int i=0;i<msg.length();i++) {
temp= new BigInteger(Integer.toString(num[i]));
temp= temp.pow(e);
temp= temp.mod(new BigInteger(Integer.toString(n)));
ed[i]=temp.intValue();
}
System.out.println("encrypted data");
for(int i=0;i<msg.length();i++)
System.out.println(ed[i]);
System.out.println();
for(int i=0;i<msg.length();i++) {
temp= new BigInteger(Integer.toString(ed[i]));
temp= temp.pow(d);
temp= temp.mod(new BigInteger(Integer.toString(n)));
dd[i]=temp.intValue();
}
System.out.println("Dencrypted data");
for(int i=0;i<msg.length();i++)
System.out.println((char)(dd[i]+'a'-1));
System.out.println();

}
public static void main(String[] args) {
System.out.println("Enter the msg");
msg= scan.next();
rsaAlg(msg);
}

}
5 DES
package des;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.util.Scanner;

public class DES {

private static final String UNICODE_FORMAT = "UTF8";


public static final String DES_ENCRYPTION_SCHEME = "DES";
private KeySpec myKeySpec;
private SecretKeyFactory mySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;

public DES(String myEncKey) throws Exception


{
myEncryptionKey = myEncKey;
myEncryptionScheme = DES_ENCRYPTION_SCHEME;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
myKeySpec = new DESKeySpec(keyAsBytes);
mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = mySecretKeyFactory.generateSecret(myKeySpec);
}

public String encrypt(String unencryptedString)


{
String encryptedString = null;
try
{
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
BASE64Encoder base64encoder = new BASE64Encoder();
encryptedString = base64encoder.encode(encryptedText);
} catch (InvalidKeyException | UnsupportedEncodingException | IllegalBlockSizeException |
BadPaddingException e) {
}
return encryptedString;
}
public String decrypt(String encryptedString)
{
String decryptedText = null;
try
{
cipher.init(Cipher.DECRYPT_MODE, key);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText = byte2String(plainText);
} catch (InvalidKeyException |IOException | IllegalBlockSizeException | BadPaddingException
e) {
}
return decryptedText;
}

private static String byte2String(byte[] bytes)


{
StringBuilder stringBuffer = new StringBuilder();
for(int i =0 ; i < bytes.length ; i++)
{
stringBuffer.append((char) bytes[i]);
}
return stringBuffer.toString();
}

public static void main(String[] args) throws Exception{


Scanner sc = new Scanner(System.in);
System.out.println("Enter the key");
String x = sc.nextLine();
DES myEncryptor = new DES(x);
System.out.println("Enter the String to encrypt");

String stringToEncrypt = sc.nextLine();


String encrypted = myEncryptor.encrypt(stringToEncrypt);
String decrypted = myEncryptor.decrypt(encrypted);
System.out.println("Encrypted Value:\n" + encrypted);
System.out.println("This is length of encrypted value:\n" + encrypted.length());
System.out.println("Decrypted Value:\n" + decrypted);
System.out.println("This is length of decrypted value:\n" + decrypted.length());
}
}
6 RSA Text File
import java.util.*;
import java.io.*;
import java.math.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class PrgRsa {

static int p,q,n,z,e,d;


static BigInteger temp;
static String msg;
static int gcd(int a, int b) {
if(a==0)
return b;
return gcd(b%a,a);
}
static void rsaAlg(String msg) throws IOException {
p=7;
q=11;
n=p*q;
z=(p-1)*(q-1);
for(int i=2;i<z;i++)
if(gcd(i,z)==1) {
e=i;
break;
}
for(int i=2;i<z;i++)
if((e*i)%z==1) {
d=i;
break;
}
//System.out.println("p="+p+ "q="+q+ "\nn="+n+ "z="+z+
// "\ne=" +e+"d=" +d);
//System.out.println(msg.length());
int num[]= new int[msg.length()];
int ed[]= new int[msg.length()];
//int dd[]= new int[msg.length()];
for(int i=0;i<msg.length();i++)
num[i]=msg.charAt(i)-'a'+1;
for(int i=0;i<msg.length();i++) {
temp= new BigInteger(Integer.toString(num[i]));
temp= temp.pow(e);
temp= temp.mod(new BigInteger(Integer.toString(n)));
ed[i]=temp.intValue();
}
System.out.println("encrypted data");
for(int i=0;i<msg.length();i++)
System.out.println(ed[i]);
PrintWriter pr = new PrintWriter("/home/ubuntu/Desktop/out");
pr.println(Arrays.toString(ed));
pr.close();
System.out.println();
/*for(int i=0;i<msg.length();i++) {
temp= new BigInteger(Integer.toString(ed[i]));
temp= temp.pow(d);
temp= temp.mod(new BigInteger(Integer.toString(n)));
dd[i]=temp.intValue();
}
System.out.println("Dencrypted data");
for(int i=0;i<msg.length();i++)
System.out.println((char)(dd[i]+'a'-1));
System.out.println();
*/
}
public static String readFileAsString(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception
{
String msg = readFileAsString("/home/ubuntu/Desktop/input");
//System.out.println(msg);
//System.out.println(msg.length());
rsaAlg(msg);
}

7 Deffiee Hellmon
package program;
import java.math.BigInteger;
import java.util.Scanner;

public class DiffieHellman {


final static BigInteger one=new BigInteger("1");
public static void main(String args[]){
Scanner stdin=new Scanner(System.in);
BigInteger p;
System.out.println("enter the value of p you want");
String ans=stdin.next();
p=getNextprime(ans);
System.out.println("your prime is"+p+".");
System.out.println("now enter number between 2 and p-1");
BigInteger g=new BigInteger(stdin.next());
System.out.println("person A secreat key");
BigInteger a=new BigInteger(stdin.next());
BigInteger resulta=g.modPow(a,p);
System.out.println("person a sends to B"+resulta+".");
System.out.println("person B secreat key");
BigInteger b=new BigInteger(stdin.next());
BigInteger resultb=g.modPow(b,p);
System.out.println("person B sends person A"+resultb+".");
BigInteger keyAcalculate=resultb.modPow(a,p);
BigInteger keyBcalculate=resulta.modPow(b,p);
System.out.println("a takes "+resultb+" raises to the power "+a+" mod"+p);
System.out.println("b takes "+resulta+" raises to the power "+b+" mod"+p);
System.out.println("the key A calculates is "+keyAcalculate+".");
System.out.println("the key B calculates is "+keyBcalculate+".");
}
public static BigInteger getNextprime(String ans){
BigInteger test=new BigInteger(ans);
while(!test.isProbablePrime(99)){
test=test.add(one);
}
return test;
}
}
8(a) MD 5

importjava.math.BigInteger;
importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
importjava.util.Scanner;

public class MD5 {


public static String getMd5(String input)
{
try {

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
returnhashtext;
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}

public static void main(String args[]) throws NoSuchAlgorithmException


{
System.out.println("hashCode Generated by MD5 for:");
String s1 = "The MD5 hash function was originally designed for use as a secure
cryptographic hash algorithm for authenticating digital signatures ";
System.out.println("s1:" + getMd5(s1));
System.out.println("enter the second string:");
Scanner sc = new Scanner(System.in);
String s2=sc.nextLine();
System.out.println("s2:" + getMd5(s2));
sc.close();

}
}

8(b) SHA-1
importjava.math.BigInteger;
importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
importjava.util.Scanner;

public class SHA {


public static String encryptThisString(String input)
{
try {

MessageDigest md = MessageDigest.getInstance("SHA");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
returnhashtext;
}
catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);
}
}
public static void main(String args[]) throws NoSuchAlgorithmException
{
System.out.println("HashCode Generated by SHA-1 for: ");
String s1 = "SHA-1 is commonly used in cryptographic applications and environments
where the need for data integrity is high.";
System.out.println("s1:" + encryptThisString(s1));
System.out.println("enter the second string:");
Scanner sc = new Scanner(System.in);
String s2=sc.nextLine();
System.out.println("s2:" + encryptThisString(s2));
sc.close();

}
}

9 NS 3 Node Point to Point


set ns [new Simulator] /* Letter S is capital */
set nf [open lab1.nam w] /* open a nam trace file in write mode */
$ns namtrace-all $nf /* nf – nam file */
set tf [open lab1.tr w] /* tf- trace file */
$ns trace-all $tf
proc finish { } { /* provide space b/w proc and finish and all are in small case */
global ns nf tf
$ns flush-trace /* clears trace file contents */
close $nf
close $tf
exec nam lab1.nam &
exit 0
}
set n0 [$ns node] /* creates 4 nodes */
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns duplex-link $n0 $n2 200Mb 10ms DropTail /*Letter M is capital Mb*/
$ns duplex-link $n1 $n2 100Mb 5ms DropTail /*D and T are capital*/
$ns duplex-link $n2 $n3 1Mb 1000ms DropTail
$ns queue-limit $n0 $n2 10
$ns queue-limit $n1 $n2 10
set udp0 [new Agent/UDP] /* Letters A,U,D and P are capital */
$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR] /* A,T,C,B and R are capital*/
$cbr0 set packetSize_ 500 /*S is capital, space after underscore*/
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
set udp2 [new Agent/UDP]
$ns attach-agent $n2 $udp2
set cbr2 [new Application/Traffic/CBR]
$cbr2 attach-agent $udp2
set null0 [new Agent/Null] /* A and N are capital */
$ns attach-agent $n3 $null0
$ns connect $udp0 $null0
$ns connect $udp1 $null0
$ns at 0.1 "$cbr0 start"
$ns at 0.2 "$cbr1 start"
$ns at 1.0 "finish"
$ns run

AWK FILE
BEGIN {
c=0;
}
{
If ($1= ="d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
}
/*immediately after END should open braces ‘{‘
END{
printf("The number of packets dropped =%d\n",c);
}

10 NS 4 Node Point to Point

set ns [new Simulator]


set nf [open lab2.nam w]
$ns namtrace-all $nf
set tf [open lab2.tr w]
$ns trace-all $tf
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab2.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns duplex-link $n0 $n2 10Mb 1ms DropTail
$ns duplex-link $n1 $n2 10Mb 1ms DropTail
$ns duplex-link $n2 $n3 10Mb 1ms DropTail
set tcp0 [new Agent/TCP] # letters A,T,C,P are capital
$ns attach-agent $n0 $tcp0
set udp1 [new Agent/UDP] # letters A,U,D,P are capital
$ns attach-agent $n1 $udp1
set null0 [new Agent/Null] # letters A and N are capital
$ns attach-agent $n3 $null0
set sink0 [new Agent/TCPSink] # letters A,T,C,P,S are capital
$ns attach-agent $n3 $sink0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
$ns connect $tcp0 $sink0
$ns connect $udp1 $null0
$ns at 0.1 "$cbr1 start"
$ns at 0.2 "$ftp0 start"
$ns at 0.5 "finish"
$ns run

AWK FILE
BEGIN{
udp=0;
tcp=0;
}
{
if($1= = “r” && $5 = = “cbr”)
{
udp++;
}
else if($1 = = “r” && $5 = = “tcp”)
{
tcp++;
}
}
END{
printf(“Number of packets sent by TCP = %d\n”, tcp);
printf(“Number of packets sent by UDP=%d\n”,udp);
}

IOT Programs

exp 1 2 3
import serial
#For Serial Communication
import time
#For Delay Function
ser= serial.Serial('/dev/ttyS0', baudrate=9600, timeout=3.0)

while True:
ser.write('Hello User A \r\n')
exp 4
import bme280
import I2C_LCD_driver
from time import *

(chip_id, chip_version) = bme280.readBME280ID()

print "Chip ID :", chip_id


print "Version :", chip_version

mylcd = I2C_LCD_driver.lcd()
temperature,pressure,humidity = bme280.readBME280All()

print "Temperature : ", temperature, "C"


print "Pressure : ", pressure, "hPa"
print "Humidity : ", humidity, "%"

mylcd.lcd_display_string("BME280", 1)
sleep(1)

mylcd.lcd_clear()
mylcd.lcd_display_string('C=' + str(temperature ) , 1)
sleep(2)
mylcd.lcd_clear()
mylcd.lcd_display_string('hPa=' + str(pressure ) , 1)
sleep(2)

mylcd.lcd_clear()
mylcd.lcd_display_string('%=' + str(humidity ) , 1)
sleep(2)

Commands
minicom -b 9600 -o -D /dev/ttyS0

i2cdetect -y 1

END

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy