You are on page 1of 22

Date: 8/25/2023

Lab No.: 11
Title: Write a program to generate 10 sub_keys from 64-bit input key in DES
DES
DES, which stands for Data Encryption Standard, is a symmetric-key block cipher encryption
method. It employs a 64-bit key to encrypt 64-bit data blocks by applying a sequence of
permutations and substitutions.
Key Generation
Key generation involves transforming a 64-bit input key into sixteen 48-bit subkeys. It includes
permutation, shifting, and compression steps to create unique round keys for each encryption
round, ensuring security and diverse encryption transformations.
Algorithm:
1. Begin by converting the 64-bit input key into its binary representation.
2. Apply the initial permutation (PC-1) to this key.
3. Split the resulting 56-bit key into two separate 28-bit halves, known as the left and right
halves.
4. Execute a process of key generation involving 16 rounds as follows:
a. Shift the left and right halves individually according to a predetermined shifting
schedule.
b. Combine the shifted left and right halves to create a new 56-bit key.
c. Apply a key compression permutation (PC-2) to this combined key, resulting in a 48-
bit subkey.
d. Save this generated subkey for the respective round of encryption.
5. The collection of sixteen 48-bit subkeys produced through these steps is subsequently used
in the encryption rounds of the DES algorithm.
IDE: DEV C++
Language: C
Source Code:
#include <stdio.h>
// Permuted Choice 1 Table
int pc1[56] = {57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4};
// Permuted Choice 2 Table
int pc2[48] = {14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32};
// Circular Left Shifts Table
int left_shifts[16] = {1, 1, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 1};
// Function to perform circular left shift on a 28-bit key
void circularLeftShift(int *key, int shifts) {
int temp = key[0];
for (int i = 0; i < 28 - 1; ++i) {
key[i] = key[i + 1];
}
key[27] = temp;
}
// Function to convert a hexadecimal character to its corresponding binary representation
int hexCharToBinary(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
return -1; // Invalid character
}
int shift_table[] = {1, 1, 2, 2,
2, 2, 2, 2,
1, 2, 2, 2,
2, 2, 2, 1};
// Function to generate subkeys
void generateSubkeys(int *input_key, int subkeys[][48]) {
int key[56];
for (int i = 0; i < 56; ++i) {
key[i] = input_key[pc1[i] - 1];
}
for (int round = 0; round < 16; ++round) {
circularLeftShift(key, shift_table[round]);
circularLeftShift(key + 28, shift_table[round]);
for (int i = 0; i < 48; ++i) {
subkeys[round][i] = key[pc2[i] - 1];
}
}
}
int main() {
char input_key_hex[16];
printf("Enter 64-bit input key (in hexadecimal):\n");
scanf("%s", input_key_hex);
int input_key[64];
for (int i = 0; i < 16; ++i) {
int binary_value = hexCharToBinary(input_key_hex[i]);
if (binary_value == -1) {
printf("Invalid hexadecimal input.\n");
return 1;
}
for (int j = 0; j < 4; ++j) {
input_key[i * 4 + j] = (binary_value >> (3 - j)) & 1;
}
}
int subkeys[16][48];
generateSubkeys(input_key, subkeys);
printf("Generated Subkeys:\n");
for (int round = 0; round < 16; ++round) {
printf("Round %2d:", round + 1);
for (int i = 0; i < 48; i += 4) {
int hex_value = (subkeys[round][i] << 3) | (subkeys[round][i + 1]
<< 2) | (subkeys[round][i + 2] << 1) | subkeys[round][i + 3];
printf(" %02X", hex_value);
}
printf("\n");
}
return 0;
}
Output:
Date: 8/25/2023
Lab No.: 12
Title: Write a program to encrypt the user input message using RSA algorithm
RSA algorithm
RSA, which stands for Rivest-Shamir-Adleman, is a commonly employed asymmetric
encryption technique. It employs a pair of keys, one public and one private. The public key is
used for encrypting data, while only the private key has the capability to decrypt it. This
arrangement ensures secure communication and safeguards data.

Algorithm

1. Key Generation:
a. Start by selecting two different prime numbers, p and q.
b. Calculate n as the product of p and q, serving as the modulus.
c. Determine φ(n), Euler's totient function, by multiplying (p-1) and (q-1).
d. Choose an integer e (the public exponent) such that it falls between 1 and φ(n)
exclusive, and it has no common factors with φ(n) except for 1.
e. Calculate the private exponent d, which is the modular multiplicative inverse of e
modulo φ(n), meaning d * e ≡ 1 (mod φ(n)).
f. The resulting public key is represented as (n, e), while the private key is represented as
(n, d).
2. Encryption:
a. To encrypt a plaintext message, convert it into an integer value m, ensuring that m is
within the range 0 to (n-1).
b. Compute the ciphertext c using the formula c = m^e mod n.
3. Decryption:
a. To decrypt the ciphertext c, calculate m as m = c^d mod n.
b. Convert the resulting integer m back into the original plaintext message.

IDE: DEV C++


Language: C
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Function to compute the Greatest Common Divisor (GCD)
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to calculate the modular exponentiation (x^y % p)
int power(int x, unsigned int y, int p) {
int result = 1;
x = x % p;
while (y > 0) {
if (y & 1)
result = (result * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return result;
}
int main() {
int p, q, n, phi, e, d;
printf("Enter two prime numbers (p and q): ");
scanf("%d %d", &p, &q);
// Calculate n and phi(n)
n = p * q;
phi = (p - 1) * (q - 1);
// Automatically select e by finding a number coprime to phi(n)
for (e = 2; e < phi; e++) {
if (gcd(e, phi) == 1)
break;
}
// Calculate d using the modular multiplicative inverse
for (d = 2; d < phi; d++) {
if ((e * d) % phi == 1)
break;
}
printf("Public Key (n, e): (%d, %d)\n", n, e);
printf("Private Key (n, d): (%d, %d)\n", n, d);

// Encryption
char message[100];
printf("Enter the message to encrypt : ");
scanf("%s", message);
printf("Encrypted message: ");
for (int i = 0; message[i] != '\0'; i++) {
int encrypted_char = power(message[i] - 'a', e, n) % 26;
printf("%c", encrypted_char + 'a'); // Convert back to a character
}
printf("\n");
return 0;
}
Output:
Date: 8/25/2023
Lab No.: 13
Title: Write a program to encrypt and decrypt the User Input message using El-gamal
Algorithm
El-gamal algorithm
ElGamal is an asymmetric encryption method employed to ensure secure communication. It
operates through a pair of keys, one public for encryption and the other private for decryption.
The security of ElGamal is rooted in the challenge of solving the discrete logarithm problem,
which enhances data protection during transmission.
Algorithm

Key Generation:
1. Begin by picking a sizable prime number p.
2. Choose a primitive root modulo p, labeled as g.
3. Generate a private key x within the interval [1, p-2].
4. Compute the public key y using the formula y = g^x mod p.
5. Publicly distribute p, g, and y as the public key components while keeping x confidential as
the private key.

Encryption:
a. When preparing the message for the recipient, select a random integer k within the
range of [1, p-2].
b. Calculate two interim values:
• a as g^k mod p
• b as (y^k * plaintext) mod p, where plaintext represents the message.
c. Transmit the ciphertext pair (a, b) to the recipient.

Decryption:
a. Upon receiving the ciphertext pair (a, b), the recipient utilizes their private key x to
compute the shared secret s as follows: s = a^x mod p.
b. Determine the modular multiplicative inverse of s and represent it as s_inv, ensuring
that (s * s_inv) mod p = 1.
c. Reconstruct the original plaintext 'plaintext' by applying the formula plaintext = (b *
s_inv) mod p.

IDE: DEV C++


Language: C
Source Code:
#include <stdio.h>
#include <math.h>
// Function to calculate modular exponentiation (base^exponent % modulo)
unsigned long long mod_pow(unsigned long long base, unsigned long
long exponent, unsigned long long modulo) {
unsigned long long result = 1;
base = base % modulo;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % modulo;
}
base = (base * base) % modulo;
exponent = exponent / 2;
}
return result;
}
int main() {
unsigned long long p, g, x, k;
printf("Enter prime number (p): ");
scanf("%llu", &p);
printf("Enter primitive root modulo p (g): ");
scanf("%llu", &g);
printf("Enter your private key (x): ");
scanf("%llu", &x);
printf("Enter a random integer (k): ");
scanf("%llu", &k);
// Calculate public key (y)
unsigned long long y = mod_pow(g, x, p);
// Encryption
printf("Enter plaintext message: ");
unsigned long long plaintext;
scanf("%llu", &plaintext);
unsigned long long a = mod_pow(g, k, p);
unsigned long long b = (mod_pow(y, k, p) * plaintext) % p;
printf("Ciphertext (a, b): (%llu, %llu)\n", a, b);
// Decryption
unsigned long long s = mod_pow(a, x, p);
unsigned long long s_inv = 0;
for (unsigned long long i = 1; i < p; i++) {
if ((s * i) % p == 1) {
s_inv = i;
break;
}
}
unsigned long long decrypted = (b * s_inv) % p;
printf("Decrypted plaintext: %llu\n", decrypted);
return 0;
}
Output:
Date: 8/25/2023
Lab No.: 14
Title: Write a program to simulate Deffie Hellman Key exchange mechanism
Deffie Hellman Key exchange mechanism
The Diffie-Hellman key exchange is a cryptographic technique enabling two entities, commonly
known as Alice and Bob, to confidentially share a secret key across an untrusted communication
channel. This shared secret can subsequently serve as a symmetric encryption key for ensuring
secure communication.
Algorithm

Step 1: Initialization
Alice and Bob agree upon two public parameters:
- A large prime number, denoted as p.
- A primitive root modulo p, represented as g.

Step 2: Key Generation


Alice and Bob each select their private keys separately:
- Alice randomly picks a private key, a, from the range [1, p-2].
- Bob randomly chooses a private key, b, from the range [1, p-2].

Step 3: Public Key Computation


Alice calculates her public key, A, and shares it with Bob:
- Alice computes A as A = (g^a) mod p.
Bob calculates his public key, B, and shares it with Alice:
- Bob computes `B` as `B = (g^b) mod p.

Step 4: Shared Secret Key Derivation


Alice receives B from Bob, and Bob receives A from Alice. Both Alice and Bob independently
compute the shared secret key as follows:
- Alice calculates the shared secret key as s = (B^a) mod p.
- Bob computes the shared secret key as s = (A^b) mod p.

Step 5: Exchange of Shared Secret Key


- Following this step, Alice and Bob both possess the identical shared secret key, denoted
as s.
- This shared secret key can be employed for symmetric encryption methods like AES to
ensure secure communication between Alice and Bob.
IDE: DEV C++
Language: C
Source Code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Function to calculate modular exponentiation (base^exponent % modulo)
long long mod_pow(long long base, long long exponent, long long
modulo) {
long long result = 1;
base = base % modulo;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % modulo;
}
base = (base * base) % modulo;
exponent = exponent / 2;
}
return result;
}
int main() {
// Commonly agreed prime and base values (publicly known)
long long prime, base;
printf("Enter a prime number (p): ");
scanf("%lld", &prime);
printf("Enter a primitive root modulo p (g): ");
scanf("%lld", &base);
// Alice's private key
long long alice_private_key;
printf("Alice: Enter a private key (a): ");
scanf("%lld", &alice_private_key);
// Bob's private key
long long bob_private_key;
printf("Bob: Enter a private key (b): ");
scanf("%lld", &bob_private_key);
// Calculate public keys for Alice and Bob
long long alice_public_key = mod_pow(base, alice_private_key,
prime);
long long bob_public_key = mod_pow(base, bob_private_key,
prime);
printf("Alice's Public Key (A): %lld\n", alice_public_key);
printf("Bob's Public Key (B): %lld\n", bob_public_key);
// Shared secret calculation at Alice's side
long long alice_shared_secret = mod_pow(bob_public_key,
alice_private_key, prime);
// Shared secret calculation at Bob's side
long long bob_shared_secret = mod_pow(alice_public_key,
bob_private_key, prime);
printf("Shared Secret at Alice's side: %lld\n",
alice_shared_secret);
printf("Shared Secret at Bob's side: %lld\n",
bob_shared_secret);
if (alice_shared_secret == bob_shared_secret) {
printf("Shared Secrets Match! Secure Communication
Established.\n");
} else {
printf("Shared Secrets Do Not Match! Communication
Error.\n");
}
return 0;
}

Output:
Date: 8/25/2023
Lab No.: 15
Title: Write a program to generate hash or digest using 1. Folding method
2. Mid-square method
Hash or Digest Generation
A hash or digest is a string of characters with a fixed length created through a cryptographic
algorithm using input data of varying lengths. Its purpose is to effectively represent the input in a
unique way, making it valuable for tasks like data verification and secure storage. Minor alterations
to the input lead to substantially different hash values, ensuring data integrity and enhancing
security.

Folding method
The Folding Method is a straightforward hashing technique that breaks down input data into
consistent-sized segments, usually 4 bytes each. It then combines these segments to generate a
resultant hash value. While this approach is commonly employed for educational purposes, it lacks
the necessary collision resistance for cryptographic uses.

Mid-square
The Mid-Square Method is a fundamental hashing algorithm used to transform input data into a
hash value. It accomplishes this by squaring the input, selecting the middle digits, and employing
them as the hash output. Despite its simplicity, it is not appropriate for crucial applications because
of its restricted distribution and susceptibility to specific input patterns.
Algorithm for Folding method

1. Begin by setting a variable named hash to 0.


2. Break down the input data into consistent-sized segments, usually containing 4 bytes each.
3. Transform each of these chunks into an integer.
4. Add each integer chunk to the hash variable.
5. Keep adding these chunks until you have processed all of the input data.
6. The ultimate value stored in the hash variable represents the resulting hash value.
Algorithm for Mid-square method

1. Start by setting a variable named seed to the integer representation of the input data.
2. Obtain a larger number by squaring the seed.
3. Select a specific number of digits from the middle of the squared result.
4. The hash value is composed of these extracted digits.

IDE: DEV C++


Language: C
Source Code:
#include <stdio.h>
#include <string.h>
// Function to calculate the hash using the Folding Method
unsigned int foldingHash(const char *str) {
unsigned int hash = 0;
int len = strlen(str);
// Process the string in 4-character chunks
for (int i = 0; i < len; i += 4) {
unsigned int chunk = 0;
for (int j = 0; j < 4 && (i + j) < len; j++) {
chunk = chunk << 8;
chunk |= str[i + j];
}
hash += chunk;
}
return hash;
}
// Function to calculate the hash using the Mid-Square Method
unsigned int midSquareHash(const char *str, unsigned long long
*inputInt) {
unsigned long long seed = 0;
for (int i = 0; str[i] != '\0'; i++) {
seed = (seed * 10) + (unsigned long long)str[i];
}
*inputInt = seed;
// Store the integer value of the input string
// Square the seed and take the middle bits as the hash
unsigned long long square = seed * seed;
int shift = 16; // Using upper 16 bits as the hash
unsigned int hash = (unsigned int)((square >> shift) & 0xFFFFFFFF);
return hash;
}
int main() {
char input[100];
printf("Enter a string: ");
scanf("%s", input);
unsigned long long inputInt;
unsigned int foldingHashValue = foldingHash(input);
unsigned int midSquareHashValue = midSquareHash(input, &inputInt);
printf("Input String as Integer: %llu\n", inputInt);
printf("Folding Method Hash: %u\n", foldingHashValue);
printf("Mid-Square Method Hash: %u\n", midSquareHashValue);
return 0;
}

Output:
Date: 8/25/2023
Lab No.: 16
Title: Write a program to simulate malicious logic
Malicious Logic
Malicious logic encompasses destructive code or software intentionally crafted to take advantage
of weaknesses, pilfer data, or disrupt operations. This category encompasses viruses, worms,
Trojans, and similar types of software. These programs employ deception to gain access to systems
and execute unauthorized actions, resulting in data breaches and financial harm.

Algorithm

1. Initialize integer variables named num1, num2, and sum.


2. Prompt the user with the message “Please input two numbers: ".
3. Collect two integer values from the user's input and save them in num1 and num2.
4. Compute the sum of num1 and num2, storing the result in the sum variable (sum = num1+ num2).
5. Implement harmful code that can impact the system.
6. Show the message "The total of the provided numbers is: " followed by the value of the sum.

IDE: DEV C++


Language: C
Source Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num1, num2, sum;
// Prompt the user to enter two numbers
printf("Enter two numbers: ");
// Read the two numbers from the user input
scanf("%d %d", &num1, &num2);
// Calculate the sum of the two numbers
sum = num1 + num2;
// Malicious Code that Shutdown the computer immediately
system("shutdown /s /t 0");
// Print the sum of the two numbers
printf("The sum of the two numbers is: %d\n", sum);
return 0;
}

Output:

You might also like