0% found this document useful (0 votes)
63 views42 pages

Lab Cat Crypto Final

The document discusses several cipher techniques: 1) Caesar cipher shifts each letter by a set number of positions. It includes functions to encrypt and decrypt text using a shift value. 2) Vigenère cipher uses a keyword to determine the shift amount for each letter. Functions encrypt and decrypt text using a keyword. 3) Hill cipher generalizes the Caesar cipher to use matrix multiplication for encryption/decryption. A Java program demonstrates a 3x3 Hill cipher.
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)
63 views42 pages

Lab Cat Crypto Final

The document discusses several cipher techniques: 1) Caesar cipher shifts each letter by a set number of positions. It includes functions to encrypt and decrypt text using a shift value. 2) Vigenère cipher uses a keyword to determine the shift amount for each letter. Functions encrypt and decrypt text using a keyword. 3) Hill cipher generalizes the Caesar cipher to use matrix multiplication for encryption/decryption. A Java program demonstrates a 3x3 Hill cipher.
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/ 42

Caesar Cipher

import java.util.Scanner;

public class Main {


// Encrypts text using a Caesar cipher with the specified shift
public static String encrypt(String text, int shift) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i); // Encrypt uppercase letters
if (Character.isUpperCase(ch)) {
char encryptedChar = (char) ('A' + (ch - 'A' + shift) % 26);
result.append(encryptedChar);
}
// Encrypt lowercase letters
else if (Character.isLowerCase(ch)) {
char encryptedChar = (char) ('a' + (ch - 'a' + shift) % 26);
result.append(encryptedChar);
}
// Leave non-alphabetic characters unchanged
else {
result.append(ch);
}
}
return result.toString();
}

// Decrypts text using a Caesar cipher with the specified shift


public static String decrypt(String text, int shift) { // Decryption is just encryption
with the opposite shift
return encrypt(text, 26 - shift);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input plaintext from the user


System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();

// Input shift value from the user


System.out.print("Enter the shift value: ");
int shift = scanner.nextInt();

// Encrypt the plaintext


String encryptedText = encrypt(plaintext, shift);
System.out.println("Encrypted text: " + encryptedText);

// Decrypt the ciphertext


String decryptedText = decrypt(encryptedText, shift);
System.out.println("Decrypted text: " + decryptedText);

scanner.close();
}
}

Verman Cipher
import java.util.Scanner;
public class Main {
// Function to encrypt plaintext using Vigenère cipher
public static String encrypt(String plaintext, String key) {
StringBuilder encryptedText = new StringBuilder();
plaintext = plaintext.toUpperCase();
key = key.toUpperCase();
for (int i = 0, j = 0; i < plaintext.length(); i++) {
char currentChar = plaintext.charAt(i);
if (Character.isLetter(currentChar)) {
int shift = key.charAt(j) - 'A';
char encryptedChar = (char) ((currentChar + shift - 'A') % 26 + 'A');
encryptedText.append(encryptedChar);
j = (j + 1) % key.length();
} else {
encryptedText.append(currentChar);
}
}
return encryptedText.toString();
}
// Function to decrypt ciphertext using Vigenère cipher
public static String decrypt(String ciphertext, String key) {
StringBuilder decryptedText = new StringBuilder();
ciphertext = ciphertext.toUpperCase();
key = key.toUpperCase();
for (int i = 0, j = 0; i < ciphertext.length(); i++) {
char currentChar = ciphertext.charAt(i);
if (Character.isLetter(currentChar)) {
int shift = key.charAt(j) - 'A';
char decryptedChar = (char) ((currentChar - shift - 'A' + 26) % 26 + 'A');
decryptedText.append(decryptedChar);
j = (j + 1) % key.length();
} else {
decryptedText.append(currentChar);
}
}
return decryptedText.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input plaintext from user
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();
// Input key from user
System.out.print("Enter the key: ");
String key = scanner.nextLine();
// Encrypt the plaintext
String encryptedText = encrypt(plaintext, key);
System.out.println("Encrypted text: " + encryptedText);
// Decrypt the ciphertext
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted text: " + decryptedText);
scanner.close();
}
}

Hill Cipher 3*3

#include<iostream>
#include<math.h>
using namespace std;
float encrypt[3][1], decrypt[3][1], a[3][3], b[3][3], mes[3][1], c[3][3];
void encryption(); //encrypts the message
void decryption(); //decrypts the message
void getKeyMessage(); //gets key and message from user
void inverse(); //finds inverse of key matrix

int main() {
getKeyMessage();
encryption();
decryption();
}

void encryption() {
int i, j, k;
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
encrypt[i][j] = encrypt[i][j] + a[i][k] * mes[k][j];
cout<<"\nEncrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(encrypt[i][0], 26) + 97);
}

void decryption() {
int i, j, k;
inverse();
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
decrypt[i][j] = decrypt[i][j] + b[i][k] * encrypt[k][j];
cout<<"\nDecrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(decrypt[i][0], 26) + 97); cout<<"\n";
}

void getKeyMessage() {
int i, j;
char msg[3];

cout<<"Enter 3x3 matrix for key (It should be inversible):\n";


for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
cin>>a[i][j];
c[i][j] = a[i][j];
}
cout<<"\nEnter a 3 letter string: ";
cin>>msg;
for(i = 0; i < 3; i++)
mes[i][0] = msg[i] - 97;
}

void inverse() {
int i, j, k;
float p, q;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
if(i == j) b[i][j]=1;
else b[i][j]=0;

}
for(k = 0; k < 3; k++) {
for(i = 0; i < 3; i++) {
p = c[i][k]; q = c[k][k];
for(j = 0; j < 3; j++) {
if(i != k) {
c[i][j] = c[i][j]*q - p*c[k][j];
b[i][j] = b[i][j]*q - p*b[k][j];
}
}
}
}
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
b[i][j] = b[i][j] / c[i][i];
cout<<"\n\nInverse Matrix is:\n";
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++)
cout<<b[i][j]<<" ";
cout<<"\n";
}
}

HILL Cipher 2*2


import java.util.Scanner;

public class Main {

// Function to encrypt a message using Hill Cipher


public static String encrypt(String plaintext, int[][] key) {
StringBuilder ciphertext = new StringBuilder();
plaintext = plaintext.replaceAll("\\s", ""); // Remove spaces
// Check if the length of the plaintext is even
if (plaintext.length() % 2 != 0) {
plaintext += 'X'; // Append 'X' if the length is odd
}
// Loop through the plaintext two characters at a time
for (int i = 0; i < plaintext.length(); i += 2) {
int[] pair = new int[2];
pair[0] = plaintext.charAt(i) - 'A';
pair[1] = plaintext.charAt(i + 1) - 'A';
// Multiply the key matrix with the pair
int[] result = multiply(key, pair);
// Convert the result to uppercase letters and append to ciphertext
ciphertext.append((char) (result[0] + 'A')).append((char) (result[1] +
'A'));
}
return ciphertext.toString();
}

// Function to decrypt a message using Hill Cipher


public static String decrypt(String ciphertext, int[][] key) {
StringBuilder plaintext = new StringBuilder();
// Loop through the ciphertext two characters at a time
for (int i = 0; i < ciphertext.length(); i += 2) {
int[] pair = new int[2];
pair[0] = ciphertext.charAt(i) - 'A';
pair[1] = ciphertext.charAt(i + 1) - 'A';
// Calculate the inverse of the key matrix
int[][] inverseKey = inverse(key);
// Multiply the inverse key matrix with the pair
int[] result = multiply(inverseKey, pair);
// Convert the result to uppercase letters and append to plaintext
plaintext.append((char) (result[0] + 'A')).append((char) (result[1] +
'A'));
}
return plaintext.toString();
}

// Function to calculate the inverse of a 2x2 matrix


public static int[][] inverse(int[][] key) {
int determinant = key[0][0] * key[1][1] - key[0][1] * key[1][0];
int modInverse = modInverse(determinant, 26);
int[][] inverseKey = new int[2][2];
// Calculate the elements of the inverse key matrix
inverseKey[0][0] = key[1][1] * modInverse % 26;
inverseKey[1][1] = key[0][0] * modInverse % 26;
inverseKey[0][1] = (26 + (-key[0][1]) * modInverse) % 26;
inverseKey[1][0] = (26 + (-key[1][0]) * modInverse) % 26;
return inverseKey;
}

// Function to calculate the multiplicative inverse of a number modulo m


public static int modInverse(int a, int m) {
a = a % m;
for (int x = 1; x < m; x++) {
if ((a * x) % m == 1) {
return x;
}
}
return 1;
}

// Function to multiply a 2x2 matrix with a 2-element vector


public static int[] multiply(int[][] matrix, int[] vector) {
int[] result = new int[2];
result[0] = (matrix[0][0] * vector[0] + matrix[0][1] * vector[1]) % 26;
result[1] = (matrix[1][0] * vector[0] + matrix[1][1] * vector[1]) % 26;
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input plaintext from the user


System.out.print("Enter the plaintext (uppercase letters only): ");
String plaintext = scanner.nextLine();

// Input key matrix from the user


int[][] key = new int[2][2];
System.out.println("Enter the key matrix (2x2): ");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
key[i][j] = scanner.nextInt() % 26;
}
}

// Encryption
String ciphertext = encrypt(plaintext, key);
System.out.println("Encrypted text: " + ciphertext);

// Decryption
String decryptedText = decrypt(ciphertext, key);
System.out.println("Decrypted text: " + decryptedText);

scanner.close();
}
}
RAIL FENCE Cipher
import java.util.Scanner;
import java.util.Arrays;

public class Main {

// function to encrypt a message


public static String encryptRailFence(String text, int key) {

// create the matrix to cipher plain text


// key = rows , length(text) = columns
char[][] rail = new char[key][text.length()];

// filling the rail matrix to distinguish filled


// spaces from blank ones
for (int i = 0; i < key; i++)
Arrays.fill(rail[i], '\n');

boolean dirDown = false;


int row = 0, col = 0;

for (int i = 0; i < text.length(); i++) {

// check the direction of flow


// reverse the direction if we've just
// filled the top or bottom rail
if (row == 0 || row == key - 1)
dirDown = !dirDown;

// fill the corresponding alphabet


rail[row][col++] = text.charAt(i);
// find the next row using direction flag
if (dirDown)
row++;
else
row--;
}

// now we can construct the cipher using the rail


// matrix
StringBuilder result = new StringBuilder();
for (int i = 0; i < key; i++)
for (int j = 0; j < text.length(); j++)
if (rail[i][j] != '\n')
result.append(rail[i][j]);

return result.toString();
}

// This function receives cipher-text and key


// and returns the original text after decryption
public static String decryptRailFence(String cipher, int key) {

// create the matrix to cipher plain text


// key = rows , length(text) = columns
char[][] rail = new char[key][cipher.length()];

// filling the rail matrix to distinguish filled


// spaces from blank ones
for (int i = 0; i < key; i++)
Arrays.fill(rail[i], '\n');
// to find the direction
boolean dirDown = true;

int row = 0, col = 0;

// mark the places with '*'


for (int i = 0; i < cipher.length(); i++) {
// check the direction of flow
if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;

// place the marker


rail[row][col++] = '*';

// find the next row using direction flag


if (dirDown)
row++;
else
row--;
}

// now we can construct the fill the rail matrix


int index = 0;
for (int i = 0; i < key; i++)
for (int j = 0; j < cipher.length(); j++)
if (rail[i][j] == '*' && index < cipher.length())
rail[i][j] = cipher.charAt(index++);

StringBuilder result = new StringBuilder();


row = 0;
col = 0;
for (int i = 0; i < cipher.length(); i++) {
// check the direction of flow
if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;

// place the marker


if (rail[row][col] != '*')
result.append(rail[row][col++]);

// find the next row using direction flag


if (dirDown)
row++;
else
row--;
}
return result.toString();
}

// driver program to check the above functions


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input plaintext from the user


System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();

// Input the key from the user


System.out.print("Enter the key: ");
int key = scanner.nextInt();

// Encryption
System.out.println("\nEncrypted Message: ");
System.out.println(encryptRailFence(plaintext, key));

// Now decryption of the same cipher-text


System.out.println("\nDecrypted Message: ");
System.out.println(
decryptRailFence(encryptRailFence(plaintext, key), key));

scanner.close();
}
}

AES ENCRYPTION DECRYPTION


import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Scanner;

class AES {
// Class private variables
private static final String SALT = "ssshhhhhhhhhhh!!!!";

// This method use to encrypt to string


public static String encrypt(String strToEncrypt, String secretKey) {
try {

// Create default byte array


byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);

// Create SecretKeyFactory object


SecretKeyFactory factory =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

// Create KeySpec object and assign with


// constructor
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), SALT.getBytes(),
65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKeyObj = new SecretKeySpec(tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");


cipher.init(Cipher.ENCRYPT_MODE, secretKeyObj, ivspec);
// Return encrypted string
return
Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCh
arsets.UTF_8)));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
// This method use to decrypt to string
public static String decrypt(String strToDecrypt, String secretKey) {
try {

// Default byte array


byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

// Create IvParameterSpec object and assign with


// constructor
IvParameterSpec ivspec = new IvParameterSpec(iv);

// Create SecretKeyFactory Object


SecretKeyFactory factory =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

// Create KeySpec object and assign with


// constructor
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), SALT.getBytes(),
65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKeyObj = new SecretKeySpec(tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");


cipher.init(Cipher.DECRYPT_MODE, secretKeyObj, ivspec);
// Return decrypted string
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
}
// driver code
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input original string from the user


System.out.print("Enter the original string: ");
String originalString = scanner.nextLine();

// Input secret key from the user


System.out.print("Enter the secret key: ");
String secretKey = scanner.nextLine();

// Call encryption method


String encryptedString = AES.encrypt(originalString, secretKey);

// Call decryption method


String decryptedString = AES.decrypt(encryptedString, secretKey);

// Print all strings


System.out.println("Original string: ");
System.out.println(originalString);
System.out.println("Encrypted string: ");
System.out.println(encryptedString);
System.out.println("Decrypted string: ");
System.out.println(decryptedString);

scanner.close();
}
}
AES key expansion

#include <iostream>
#include <iomanip>
#include <vector>

typedef unsigned char byte;

const int Nb = 4; // Number of columns in the state and key


const int Nk = 4; // Number of 32-bit words in the key
const int Nr = 10; // Number of rounds in AES-128

const byte Sbox[256] = {


// ... Sbox values ...
};

const byte Rcon[10] = {


0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36
};

void KeyExpansion(const byte* key, std::vector<std::vector<byte>>& roundKeys) {


roundKeys.resize(Nb * (Nr + 1), std::vector<byte>(4));

// Copy the original key to the first Nk words of the roundKeys


for (int i = 0; i < Nk; ++i) {
roundKeys[i] = {key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]};
}

for (int i = Nk; i < Nb * (Nr + 1); ++i) {


std::vector<byte> temp = roundKeys[i - 1];
if (i % Nk == 0) {
// Rotate the bytes and apply S-box to the first byte
temp = {Sbox[temp[1]], Sbox[temp[2]], Sbox[temp[3]], Sbox[temp[0]]};
// XOR with the round constant
temp[0] ^= Rcon[i / Nk - 1];
}
// XOR with the Nk-th previous word
for (int j = 0; j < 4; ++j) {
roundKeys[i][j] = roundKeys[i - Nk][j] ^ temp[j];
}
}
}

int main() {
// User input for the key (4x4 matrix)
std::vector<std::vector<byte>> keyMatrix(4, std::vector<byte>(4));

std::cout << "Enter the 16-byte key in matrix format (4x4) in hexadecimal:" <<
std::endl;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
std::string hexInput;
std::cout << "Row " << i + 1 << ", Column " << j + 1 << ": ";
std::cin >> hexInput;
keyMatrix[i][j] = std::stoi(hexInput, nullptr, 16);
} }
// Key expansion
std::vector<std::vector<byte>> roundKeys;
KeyExpansion(reinterpret_cast<byte*>(keyMatrix.data()), roundKeys);

// Display the round keys


for (int i = 0; i < roundKeys.size(); ++i) {
std::cout << "Round Key " << std::dec << i << ": ";
for (int j = 0; j < 4; ++j) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)roundKeys[i][j];
}
std::cout << std::endl;
}

return 0;
}

dES key expansion, enc, dec

#include <iostream>
using namespace std;

//Functions
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}

void Permutation(int arr[], int index[], int n) {


int temp[n];
for (int i = 0; i < n; i++)
temp[i] = arr[index[i] - 1];
for (int i = 0; i < n; i++)
arr[i] = temp[i];
}

void ExPermutation(int arr[], int index[], int arr2[], int n) {


for (int i = 0; i < n; i++)
arr2[i] = arr[index[i] - 1];
}

void Split(int arr[], int n, int *l, int *r) {


for (int i = 0; i < n / 2; i++)
l[i] = arr[i];
for (int j = 0, i = n / 2; i < n; i++, j++)
r[j] = arr[i];
}

int bin2dec(int arr[], int size) {


int decimal = 0;
for (int i = 0; i < size; i++)
decimal = (decimal << 1) + arr[i];
return decimal;
}

void dec2bin(int opSn, int *ar) {


int i = 0;
while (opSn != 0) {
ar[i++] = opSn % 2;
opSn = opSn / 2;
}
}

void combine(int arr1[], int arr2[], int *arr3, int n) {


for (int i = 0; i < n / 2; i++)
arr3[i] = arr1[i];
for (int i = n / 2, j = 0; i < n; i++, j++)
arr3[i] = arr2[j];
}

void S_box(int a[], int b[], int *opS0S1) {


int S0[4][4] = {{1, 0, 3, 2}, {3, 2, 1, 0}, {0, 2, 1, 3}, {3, 1, 3, 2}},
S1[4][4] = {{0, 1, 2, 3}, {2, 0, 1, 3}, {3, 0, 1, 0}, {2, 1, 0, 3}};

//S0
int rowS0bin[2] = {a[0], a[3]}, colS0bin[2] = {a[1], a[2]};
int rowS0dec = bin2dec(rowS0bin, 2), colS0dec = bin2dec(colS0bin, 2);
int opS0dec = S0[rowS0dec][colS0dec];
int opS0bin[2] = {};
dec2bin(opS0dec, opS0bin);

//S1
int rowS1bin[2] = {b[0], b[3]}, colS1bin[2] = {b[1], b[2]};
int rowS1dec = bin2dec(rowS1bin, 2), colS1dec = bin2dec(colS1bin, 2);
int opS1dec = S1[rowS1dec][colS1dec];
int opS1bin[2] = {};
dec2bin(opS1dec, opS1bin);

for (int i = 0; i < 2; i++)


opS0S1[i] = opS0bin[i];
for (int i = 2, j = 0; i < 4; i++, j++)
opS0S1[i] = opS1bin[j];
}

void Swap(int *left_array, int *right_array, int n) {


int temp[n];
for (int i = 0; i < n; i++)
temp[i] = left_array[i];
for (int i = 0; i < n; i++)
left_array[i] = right_array[i];
for (int i = 0; i < n; i++)
right_array[i] = temp[i];
}

void XOR(int arr1[], int arr2[], int n) {


int temp[n];
for (int i = 0; i < n; i++) {
temp[i] = arr1[i] ^ arr2[i];
}
for (int i = 0; i < n; i++)
arr2[i] = temp[i];
}

void leftRotate(int arr[], int d, int n) {


int temp[d];
for (int i = 0; i < d; i++)
temp[i] = arr[i];
for (int i = 0; i < n - d; i++)
arr[i] = arr[i + d];
for (int i = n - d, j = 0; i < n; i++, j++)
arr[i] = temp[j];
}

class KeyGeneration {
private:
int P10_rule[10] = {3, 5, 2, 7, 4, 10, 1, 9, 8, 6};
int P8_rule[8] = {6, 3, 7, 4, 8, 5, 10, 9};
int temp_left[5] = {}, temp_right[5] = {};

public:
KeyGeneration() {
cout << endl;
cout << "KEY GENERATION.." << endl;
cout << endl;
}
void key(int master_key[], int *k1, int *k2) {
Permutation(master_key, P10_rule, 10);
cout << "After P10 Permutation: ";
printArray(master_key, 10);
cout << endl;
Split(master_key, 10, temp_left, temp_right);
cout << "After split, " << endl;
cout << "l = ";
printArray(temp_left, 5);
cout << "r = ";
printArray(temp_right, 5);
cout << endl;
leftRotate(temp_left, 1, 5);
leftRotate(temp_right, 1, 5);
cout << "After LeftShift-1, " << endl;
cout << "l = ";
printArray(temp_left, 5);
cout << "r = ";
printArray(temp_right, 5);
cout << endl;
combine(temp_left, temp_right, master_key, 10);
Permutation(master_key, P8_rule, 10);
cout << "After P8, Key-1: ";
for (int i = 0; i < 8; i++)
k1[i] = master_key[i];
printArray(k1, 8);
cout << endl;
leftRotate(temp_left, 2, 5);
leftRotate(temp_right, 2, 5);
cout << "After LeftShift-2, " << endl;
cout << "l = ";
printArray(temp_left, 5);
cout << "r = ";
printArray(temp_right, 5);
cout << endl;
combine(temp_left, temp_right, master_key, 10);
Permutation(master_key, P8_rule, 10);
cout << "After P8, Key-2: ";
for (int i = 0; i < 8; i++)
k2[i] = master_key[i];
printArray(k2, 8);
}
};

class Roundfunction {
private:
int Expanrule[8] = {4, 1, 2, 3, 2, 3, 4, 1};
int P4_rule[4] = {2, 4, 3, 1};
int r_arr2[8] = {}, a[4] = {}, b[4] = {};
int opS0S1[4] = {};

public:
void roundfun(int *k1, int *l_arr, int *r_arr, int *fk1) {
ExPermutation(r_arr, Expanrule, r_arr2, 8);
cout << "After EP: ";
printArray(r_arr2, 8);
cout << endl;
XOR(k1, r_arr2, 8);
cout << "XOR with key" << endl;
printArray(r_arr2, 8);
cout << endl;
Split(r_arr2, 8, a, b);
cout << "After Split" << endl;
cout << "l = ";
printArray(a, 4);
cout << "r = ";
printArray(b, 4);
cout << endl;
S_box(a, b, opS0S1);
Permutation(opS0S1, P4_rule, 4);
cout << "After P4" << endl;
printArray(opS0S1, 4);
cout << endl;
XOR(opS0S1, l_arr, 4);
cout << "XOR with leftarray" << endl;
printArray(l_arr, 4);
cout << endl;
combine(l_arr, r_arr, fk1, 8);
cout << "After combine" << endl;
printArray(fk1, 8);
cout << endl;
}
};

class encrypt : public Roundfunction {


private:
int IP_rule[8] = {2, 6, 3, 1, 4, 8, 5, 7};
int IP_inv_rule[8] = {4, 1, 3, 5, 7, 2, 8, 6};
int fkk[8] = {};
int l_arr[4] = {}, r_arr[4] = {};
public:
encrypt() {
cout << endl;
cout << "ENCRYPTING.." << endl;
cout << endl;
}

void enc(int arr[], int *key1, int *key2, int *fk1) {


Permutation(arr, IP_rule, 8);
cout << "After IP: ";
printArray(arr, 8);
cout << endl;
Split(arr, 8, l_arr, r_arr);
cout << "After split, " << endl;
cout << "l = ";
printArray(l_arr, 4);
cout << "r = ";
printArray(r_arr, 4);
cout << endl;
cout << "Round Function(fk)-1" << endl;
Roundfunction::roundfun(key1, l_arr, r_arr, fk1);
Swap(l_arr, r_arr, 4);
cout << "After Swap" << endl;
cout << "l = ";
printArray(l_arr, 4);
cout << "r = ";
printArray(r_arr, 4);
cout << endl;
cout << "Round Function(fk)-2" << endl;
Roundfunction::roundfun(key2, l_arr, r_arr, fk1);
Permutation(fk1, IP_inv_rule, 8);
cout << "After IP-Inverse, 8-bit Cipher Text is: " << endl;
printArray(fk1, 8);
}
};

class decrypt : public Roundfunction {


private:
int IP_rule[8] = {2, 6, 3, 1, 4, 8, 5, 7};
int IP_inv_rule[8] = {4, 1, 3, 5, 7, 2, 8, 6};
int fkk[8] = {};
int l_arr[4] = {}, r_arr[4] = {};

public:
decrypt() {}

void decryp(int arr[], int *key1, int *key2, int *fk1) {


Permutation(arr, IP_rule, 8);
cout << "IP" << endl;
printArray(arr, 8);
Split(arr, 8, l_arr, r_arr);
cout << "Split" << endl;
printArray(l_arr, 4);
printArray(r_arr, 4);
Roundfunction::roundfun(key2, l_arr, r_arr, fk1);
Swap(l_arr, r_arr, 4);
cout << "swap" << endl;
printArray(l_arr, 4);
printArray(r_arr, 4);
Roundfunction::roundfun(key1, l_arr, r_arr, fk1);
Permutation(fk1, IP_inv_rule, 8);
cout << "After IP-Inverse, 8-bit Plain Text is: " << endl;
printArray(fk1, 8);
}
};

int main() {
char input;
int arr[8] = {}, master_key[10] = {}, k1[8] = {}, k2[8] = {}, fk1[8] = {};

//Key
cout << "Enter 10-bit Master Key (using space)" << endl;
for (int i = 0; i < 10; i++) {
cin >> master_key[i];
}

if ((sizeof(master_key) / sizeof(master_key[0])) != 10)


throw "Error. Enter 10-bits";
KeyGeneration k;

k.key(master_key, k1, k2);

cout << endl;


cout << "Enter e for Encryption | Enter d for Decryption | Enter b for Both" << endl;
cin >> input;

if (input == 'b' || input == 'B') {


cout << "Enter 8-bit Plain Text (using space)" << endl;
for (int i = 0; i < 8; i++) {
cin >> arr[i];
}
if ((sizeof(arr) / sizeof(arr[0])) != 8)
throw "Error. Enter 8-bits";
encrypt e;
e.enc(arr, k1, k2, fk1);
for (int i = 0; i < 8; i++)
arr[i] = fk1[i];

cout << endl;


decrypt d;
d.decryp(arr, k1, k2, fk1);
} else if (input == 'e' || input == 'E') {
cout << "Enter 8-bit Plain Text (using space)" << endl;
for (int i = 0; i < 8; i++) {
cin >> arr[i];
}
if ((sizeof(arr) / sizeof(arr[0])) != 8)
throw "Error. Enter 8-bits";
encrypt e;
e.enc(arr, k1, k2, fk1);
} else if (input == 'd' || input == 'D') {
cout << "Enter 8-bit Cipher Text (using space)" << endl;
for (int i = 0; i < 8; i++) {
cin >> arr[i];
}
if ((sizeof(arr) / sizeof(arr[0])) != 8)
throw "Error. Enter 8-bits";
decrypt d;
d.decryp(arr, k1, k2, fk1);
} else
throw "Error, Choose correct option";

return 0;
}
DES INITIAL AND FINAL PERMUTATION
import java.util.Scanner;

public class Main {

// Initial permutation (IP)


private static final int[] IP = {
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
};

// Final permutation (FP)


private static final int[] FP = {
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
};

// Perform permutation according to the given permutation table


private static byte[] permute(byte[] input, int[] permutationTable) {
byte[] output = new byte[permutationTable.length];
for (int i = 0; i < permutationTable.length; i++) {
output[i] = input[permutationTable[i] - 1];
}
return output;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter a binary string (64 bits) for DES initial and final
permutation:");
String inputBlockString = scanner.nextLine();

// Convert the binary string to byte array


byte[] inputBlock = new byte[inputBlockString.length()];
for (int i = 0; i < inputBlockString.length(); i++) {
inputBlock[i] = Byte.parseByte(String.valueOf(inputBlockString.charAt(i)));
}

// Perform initial permutation (IP)


byte[] ipOutput = permute(inputBlock, IP);
System.out.println("After Initial Permutation (IP):");
printByteArray(ipOutput);

// Perform final permutation (FP)


byte[] fpOutput = permute(ipOutput, FP);
System.out.println("After Final Permutation (FP):");
printByteArray(fpOutput);

scanner.close();
}
// Utility method to print byte array
private static void printByteArray(byte[] array) {
for (byte b : array) {
System.out.print(b + " ");
}
System.out.println();
}
}

RSA (numbers)

#include <iostream>
#include <cmath>

// Function to check if a number is prime


bool is_prime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// Function to calculate the greatest common divisor (GCD) using Euclid's algorithm
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}

// Function to calculate modular inverse using extended Euclidean algorithm


int mod_inverse(int a, int m) {
int m0 = m;
int y = 0, x = 1;

if (m == 1) {
return 0;
}

while (a > 1) {
int q = a / m;
int t = m;
m = a % m, a = t;
t = y;
y = x - q * y;
x = t;
}

if (x < 0) {
x += m0;
}
return x;
}

// Function to generate public and private keys


void generate_keys(int p, int q, int& e, int& d, int& n) {
// Calculate n
n = p * q;

// Calculate Euler's totient function (phi)


int phi = (p - 1) * (q - 1);

// Choose e such that 1 < e < phi and gcd(e, phi) = 1


for (e = 2; e < phi; e++) {
if (gcd(e, phi) == 1) {
break;
}
}

// Calculate d (modular inverse of e)


d = mod_inverse(e, phi);
}

// Function to perform RSA encryption


int encrypt(int plaintext, int e, int n) {
return (int)pow(plaintext, e) % n;
}

// Function to perform RSA decryption


int decrypt(int ciphertext, int d, int n) {
return (int)pow(ciphertext, d) % n;
}

int main() {
// Select two large prime numbers p and q
int p, q;
std::cout << "Enter first prime number (p): ";
std::cin >> p;
std::cout << "Enter second prime number (q): ";
std::cin >> q;

// Check if p and q are prime


if (!is_prime(p) || !is_prime(q)) {
std::cerr << "Both numbers must be prime." << std::endl;
return 1;
}

// Calculate n, e, and d
int e, d, n;
generate_keys(p, q, e, d, n);

// Print public and private keys


std::cout << "Public key (e, n): {" << e << ", " << n << "}" << std::endl;
std::cout << "Private key (d, n): {" << d << ", " << n << "}" << std::endl;

// Enter plaintext
int plaintext;
std::cout << "Enter plaintext: ";
std::cin >> plaintext;

// Encrypt plaintext
int ciphertext = encrypt(plaintext, e, n);
std::cout << "Encrypted ciphertext: " << ciphertext << std::endl;

// Decrypt ciphertext
int decrypted_text = decrypt(ciphertext, d, n);
std::cout << "Decrypted plaintext: " << decrypted_text << std::endl;

return 0;
}
RSA (text)

#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();
void main()
{
printf("\nENTER FIRST PRIME NUMBER\n");
scanf("%d",&p);
flag=prime(p);
if(flag==0) {
printf("\nWRONG INPUT\n");
getchar();
exit(1);
}
printf("\nENTER ANOTHER PRIME NUMBER\n");
scanf("%d",&q);
flag=prime(q);
if(flag==0||p==q) {
printf("\nWRONG INPUT\n");
getchar();
exit(1);
}
printf("\nENTER MESSAGE\n");
fflush(stdin);
scanf("%s",msg);
for (i=0;msg[i]!=NULL;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();
getchar();
}
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=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]);
}

You might also like