0% found this document useful (0 votes)
9 views20 pages

Cns Lab Manual

Uploaded by

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

Cns Lab Manual

Uploaded by

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

CNS LAB MANUAL

1. Aim: Write a C program that contains a string (char pointer) with a value \’Hello
World’. The program should XOR each character in this string with 0 and displays the
result.

Implementation Code:
#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello World";
char str1[11]; // Make sure to allocate enough space for the null terminator
int i, len;

len = strlen(str);

for (i = 0; i < len; i++) {


str1[i] = str[i] ^ 0; // XOR operation with 0 (which is a no-op)
printf("%c", str1[i]);
}

printf("\n");

return 0;
}

Output:

Hello World

=== Code Execution Successful ===


2. Aim: Write a C program that contains a string (char pointer) with a value \Hello
World’. The program should AND, and XOR each character in this string with 127 and
display the result.
#include <stdio.h>
#include <string.h>
int main() {
char str[11] = "Hello World";
char str1[11];
char str2[11] = "Hello World";
char str3[11];
int i, len;
len = strlen(str);
// Perform str1[i] = str[i] & 127
for (i = 0; i < len; i++) {
str1[i] = str[i] & 127; // Bitwise AND with 127
printf("%c", str1[i]);
}
printf("\n");

// Perform str3[i] = str2[i] ^ 127


for (i = 0; i < len; i++) {
str3[i] = str2[i] ^ 127; // Bitwise XOR with 127
printf("%c", str3[i]);
}
printf("\n");
return 0;
}
Output:
hello world

3. Aim: Write a C program to implementation of Caesar Cipher Encryption technique.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char text[500], ch;
int key;

printf("Enter a message to encrypt: ");


fgets(text, sizeof(text), stdin);

text[strcspn(text, "\n")] = '\0';

printf("Enter the key: ");


scanf("%d", &key);

key = key % 26;

// Encrypting message
for (int i = 0; text[i] != '\0'; ++i) {
ch = text[i];

if (isalpha(ch)) {
if (islower(ch)) {
ch = 'a' + (ch - 'a' + key) % 26;
} else if (isupper(ch)) {
ch = 'A' + (ch - 'A' + key) % 26;
}
} else if (isdigit(ch)) {
ch = '0' + (ch - '0' + key) % 10;
}
// else: leave non-alphanumeric characters unchanged

text[i] = ch;
}

// Output encrypted message


printf("Encrypted message: %s\n", text);

return 0;
}

Output:
Enter a message to encrypt: yZq8NS92mdR
Enter the key: 6
Encrypted message: eFw4TY58sjX
4. Aim: Write a C program to implementation of Caesar Cipher Decryption technique.

#include<stdio.h>
#include<ctype.h>
int main() {
char text[500], ch;
int key;
// Taking user input.
printf("Enter a message to decrypt: ");
scanf("%s", text);
printf("Enter the key: ");
scanf("%d", & key);
// Visiting each character.
for (int i = 0; text[i] != '\0'; ++i) {
ch = text[i];
// Check for valid characters.
if (isalnum(ch)) {
//Lowercase characters.
if (islower(ch)) {
ch = (ch - 'a' - key + 26) % 26 + 'a';
}
// Uppercase characters.
if (isupper(ch)) {
ch = (ch - 'A' - key + 26) % 26 + 'A';
}
// Numbers.
if (isdigit(ch)) {
ch = (ch - '0' - key + 10) % 10 + '0';
}
}
// Invalid characters.
else {
printf("Invalid Message");
}
// Adding decoded character back.
text[i] = ch;
}
printf("Decrypted message: %s", text);
return 0;
}

Output:

Enter a message to decrypt: sri


Enter the key: 1
Decrypted message: rqh

• Aim: Write a C program to implement the Pure Transposition Cipher.


#include<stdio.h>
int check(int x,int y)
{
int a,b,c;
if(x%y==0)
return 0;
a=x/y;
b=y*(a+1);
c=b-x;
return c;
}
void main()
{
int l1,i,d,j;
printf("\nEnter the length of the key. ");
scanf("%d",&l1);
int sequence[l1];
printf("\nEnter the sequence key. ");
for(i=0;i<l1;++i)
{
scanf("%d",&sequence[i]);
}
int order[l1];
for(i=1;i<=l1;++i)
{
for(j=0;j<l1;++j)
{
if(sequence[j]==i)
order[i-1]=j;
}
}
printf("\nEnter the depth. ");
scanf("%d",&d);
int l2;
printf("\nEnter the length of String without spaces . ");
scanf("%d",&l2);
int temp1=check(l2,l1);
int r=(l2+temp1)/l1;
char p[l2+temp1];
char p1[r][l1];
//char p2[r][l1];
if(temp1>0)
printf("\nYou need to enter %d bogus characters.So enter total %d characters. ",temp1,
(l2+temp1));
else
printf("\nEnter the string. ");
for(i=-1;i<(l2+temp1);++i)
{
scanf("%c",&p[i]);
}
int count=0;
while(d>0)
{
count=0;
for(i=0;i<r;++i)
{
for(j=0;j<l1;++j)
{
p1[i][j]=p[count];
count=count+1;
}
}
printf("\n\n\n");
for(i=0;i<r;++i)
{
for(j=0;j<l1;++j)
{
printf("%c ",p1[i][j]);
}
printf("\n");
}
count=0;
for(i=0;i<l1;++i)
{
for(j=0;j<r;++j)
{
p[count]=p1[j][order[i]];
count=count+1;
}
}
for(i=0;i<(l2+temp1);++i)
printf("%c ",p[i]);
d=d-1;
}
}

Output:

Enter the length of the key. 7


Enter the sequence key. 4 3 1 2 5 6 7
Enter the depth. 2
Enter the length of String without spaces. 23
You need to enter 5 bogus characters. So enter total 28 characters.
attackpostponeduntiltwoamxyz
attackp
ostpone
duntilt
woamxyz
ttnaaptmtsuoaodwcoixknlypetz
ttnaapt
mtsuoao
dwcoixk
nlypetz
nscyauopttwltmdnaoiepaxttokz
6.Write a C program to implement the AES Encryption and decryption.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
public class AESEncryptionDecryption {

public static void main(String[] args) {


try{
Cipher cipher = Cipher.getInstance("AES");
KeyGenerator kg = KeyGenerator.getInstance("AES");
Key key = kg.generateKey();
cipher.init(Cipher.ENCRYPT_MODE, key);
CipherInputStream cipt=new CipherInputStream(new FileInputStream(new
File("D:\\PlainTextInput.txt")), cipher);
FileOutputStream fip=new FileOutputStream(new File("D:\\EncryptedText.txt"));
int i;
while((i=cipt.read())!=-1)
{
fip.write(i);
}
cipher.init(Cipher.DECRYPT_MODE, key);
CipherInputStream ciptt=new CipherInputStream(new FileInputStream(new
File("D:\\EncryptedText.txt")), cipher);
FileOutputStream fop=new FileOutputStream(new File("D:\\DecryptedText.txt"));
int j;
while((j=ciptt.read())!=-1)
{
fop.write(j);
}
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("Encryption and Decryption of plain text file performed successfully.");
}
}

Output:
Encryption and Decryption of plain text file performed successfully.

• Write a C program to implement RSA Encryption Algorithm.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

long int p, q, n, t, flag, e[100], d[100], temp[100], j, m[100], en[100], i;


char msg[100];
int prime(long int);
void ce();
long int cd(long int);
void encrypt();
void decrypt();

int main() {
printf("\nEnter first prime number: ");
scanf("%ld", &p);
flag = prime(p);
if (flag == 0) {
printf("\nWRONG INPUT\n");
exit(1);
}

printf("\nEnter another prime number: ");


scanf("%ld", &q);
flag = prime(q);
if (flag == 0 || p == q) {
printf("\nWRONG INPUT\n");
exit(1);
}

printf("\nEnter message to be encrypted: ");


fflush(stdin);
scanf("%s", msg);
for (i = 0; msg[i] != '\0'; i++)
m[i] = msg[i];
n = p * q;
t = (p - 1) * (q - 1);
ce();
printf("\nPossible values of e and d are:\n");
for (i = 0; i < j - 1; i++)
printf("\n%ld\t%ld", e[i], d[i]);

encrypt();
decrypt();

return 0;
}

int prime(long int pr) {


int i;
j = sqrt(pr);
for (i = 2; i <= j; i++) {
if (pr % i == 0)
return 0;
}
return 1;
}

void ce() {
int k;
k = 0;
for (i = 2; i < t; i++) {
if (t % i == 0)
continue;
flag = prime(i);
if (flag == 1 && i != p && i != q) {
e[k] = i;
flag = cd(e[k]);
if (flag > 0) {
d[k] = flag;
k++;
}
if (k == 99)
break;
}
}
}

long int cd(long int x) {


long int k = 1;
while (1) {
k = k + t;
if (k % x == 0)
return (k / x);
}
}
void encrypt() {
long int pt, ct, key = e[0], k, len;
i = 0;
len = strlen(msg);
while (i != len) {
pt = m[i];
pt = pt - 96;
k = 1;
for (j = 0; j < key; j++) {
k = k * pt;
k = k % n;
}
temp[i] = k;
ct = k + 96;
en[i] = ct;
i++;
}
en[i] = -1;
printf("\nTHE ENCRYPTED MESSAGE IS\n");
for (i = 0; en[i] != -1; i++)
printf("%c", en[i]);
}

void decrypt() {
long int pt, ct, key = d[0], k;
i = 0;
while (en[i] != -1) {
ct = temp[i];
k = 1;
for (j = 0; j < key; j++) {
k = k * ct;
k = k % n;
}
pt = k + 96;
m[i] = pt;
i++;
}
m[i] = -1;
printf("\nTHE DECRYPTED MESSAGE IS\n");
for (i = 0; m[i] != -1; i++)
printf("%c", m[i]);
}
Output:
Enter first prime number: 7
Enter another prime number: 3
Enter message to be encrypted: swetha
Possible values of e and d are:
5 5
11 11
THE ENCRYPTED MESSAGE IS
jkqtha
THE DECRYPTED MESSAGE IS
sbetha
• Write a C program to implement the Diffie-Hellman Key Exchange mechanism.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

// Function to calculate (base^exp) % mod using iterative method


long long int power_mod(long long int base, long long int exp, long long int mod) {
long long int result = 1;
while (exp > 0) {
if (exp % 2 == 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp /= 2;
}
return result;
}

// Function to perform Diffie-Hellman key exchange


long long int diffie_hellman(long long int p, long long int g, long long int a, long long int b) {
// Alice's public key
long long int A = power_mod(g, a, p);
// Bob's public key
long long int B = power_mod(g, b, p);
// Calculate shared secret
long long int s_Alice = power_mod(B, a, p);
long long int s_Bob = power_mod(A, b, p);

// Both should compute the same shared secret


if (s_Alice == s_Bob) {
return s_Alice;
} else {
return -1; // Error: Shared secret mismatch
}
}

int main() {
long long int prime_number = 23; // Example prime number
long long int primitive_root = 5; // Example primitive root modulo 23
long long int private_key_Alice = 6; // Alice's private key
long long int private_key_Bob = 15; // Bob's private key

// Perform Diffie-Hellman key exchange


long long int shared_secret = diffie_hellman(prime_number, primitive_root,
private_key_Alice, private_key_Bob);

if (shared_secret != -1) {
printf("Shared secret: %lld\n", shared_secret);
} else {
printf("Error: Shared secret calculation failed.\n");
}
return 0;
}

Output: Shared secret: 2


9.Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

import java.security.*;

public class MD5 {

public static void main(String[] args) {


try {
// Obtain an instance of MessageDigest for MD5 hashing
MessageDigest md = MessageDigest.getInstance("MD5");

System.out.println("Message digest object info:");


System.out.println("Algorithm = " + md.getAlgorithm());
System.out.println("Provider = " + md.getProvider());
System.out.println("ToString = " + md.toString());

// Input string for which MD5 hash is to be calculated


String input = "Hello, MD5!";

// Update the digest with the input string


md.update(input.getBytes());
// Calculate the MD5 hash
byte[] digest = md.digest();

// Convert byte array to hexadecimal format


StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}

// Print the MD5 hash


System.out.println("MD5 Hash: " + sb.toString());

} catch (NoSuchAlgorithmException e) {
System.err.println("MD5 algorithm not found");
e.printStackTrace();
}
}
}

output:
Message digest object info:
Algorithm = MD5
Provider = SUN version 11
ToString = MD5 Message Digest from SUN, <initialized>

MD5 Hash: 383e139e64e5f46de9d03ba3695da2d8


10. Write a C program to implementation of Hash Functions.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 20
struct DataItem {
int data;
int key;
};
struct DataItem* hashArray[SIZE];
struct DataItem* dummyItem;
struct DataItem* item;
int hashCode(int key) {
return key % SIZE;
}
struct DataItem *search(int key)
{
int hashIndex = hashCode(key);
while(hashArray[hashIndex] != NULL)
{
if(hashArray[hashIndex]->key == key)
return hashArray[hashIndex];
++hashIndex;
hashIndex %= SIZE;
}
return NULL;
}
void insert(int key,int data)
{
struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); item->data = data;
item->key = key;
int hashIndex = hashCode(key);
while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1)
{
++hashIndex;
hashIndex %= SIZE;
}
hashArray[hashIndex] = item;
}
struct DataItem* delete(struct DataItem* item)
{
int key = item->key;
int hashIndex = hashCode(key);
while(hashArray[hashIndex] != NULL)
{
if(hashArray[hashIndex]->key == key)
{
struct DataItem* temp = hashArray[hashIndex];
hashArray[hashIndex] = dummyItem;
return temp;
}
++hashIndex;
hashIndex %= SIZE;
}
return NULL;
}
void display() {
int i = 0;
for(i = 0; i<SIZE; i++)
{
if(hashArray[i] != NULL)
printf(" (%d,%d)",hashArray[i]->key,hashArray[i]->data);
else
printf(" ~~ ");
}
printf("\n");
}
int main() {
dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); dummyItem->data = -1;
dummyItem->key = -1;
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);
display();
item = search(37);
if(item != NULL)
{
printf("Element found: %d\n", item->data);
}
else
{
printf("Element not found\n");
}
delete(item);
item = search(37);
if(item != NULL)
{
printf("Element found: %d\n", item->data);
}
else
{
printf("Element not found\n");
}
}

Output:

~~ (1,20) (2,70) (42,80) (4,25) ~~ ~~ ~~ ~~ ~~ ~~ ~~ (12,44) (13,78) (14,32) ~~ ~~


(17,11) (37,97) ~~
Element found: 97
Element not found

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