Image encryption
import cv2
import numpy as np
from numpy import random
#Load original image
demo = cv2.imread("/content/cat.jpg")
r, c, t = demo.shape
#Create random key
key = random.randint(256, size = (r, c, t))
#Encryption
enc = demo ^ key
#decryption
dec = enc ^ key
cv2.imwrite("encrypted.jpg", enc)
cv2.imwrite("decrypted.jpg", dec)
cv2.imwrite("key.png", key)
Elgamal
Code1
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
bool isPrime(int n)
{
if (n == 2)
{
return true;
}
if (n % 2 == 0)
{
return false;
}
for (int i = 3; i <= sqrt(n); i += 2)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
int modPow(int base, int exponent, int mod)
{
int result = 1;
base = base % mod;
while (exponent > 0)
{
if (exponent % 2 == 1)
{
result = (result * base) % mod;
}
exponent = exponent >> 1;
base = (base * base) % mod;
}
return result;
}
pair<int, int> encrypt(int e1, int e2, int p)
{
srand(time(0));
int r = rand() % (p - 1) + 1;
cout << "Random number r is : " << r << endl;
int c1 = modPow(e1, r, p);
int m;
do
{
cout << "Enter Message m : ";
cin >> m;
} while (!(m < p));
int c2 = (m * modPow(e2, r, p)) % p;
pair<int, int> ct = make_pair(c1, c2);
cout << "Cipher text is : (" << ct.first << ", " << ct.second << ")" << endl;
return ct;
}
void decrypt(int c1, int c2, int p, int d)
{
int pt = (c2 * modPow(modPow(c1, p - 1 - d, p), 1, p)) % p;
cout << "Decrypted message is : " << pt << endl;
}
int main()
{
int p = 0;
while (!isPrime(p))
{
cout << "Select a Prime Number p : ";
cin >> p;
}
int d;
cout << "Enter private key d : ";
cin >> d;
int e1;
do
{
cout << "Enter e1 : ";
cin >> e1;
} while (!(1 < e1 && e1 < p - 1));
int e2 = modPow(e1, d, p);
cout << "Public key is : (" << e1 << ", " << e2 << ", " << p << ")" << endl;
cout << "Private key is : " << d << endl;
pair<int, int> ct = encrypt(e1, e2, p);
decrypt(ct.first, ct.second, p, d);
return 0;
}
Code2
#include <iostream>
#include <vector>
using namespace std;
int gcd(int a, int b) {
if (a < b) return gcd(b, a);
if (a % b == 0) return b;
return gcd(b, a % b);
}
int gen_key(int q) {
int key;
do {
cout << "Enter a private key (should be a large random number): ";
cin >> key;
} while (gcd(q, key) != 1);
return key;
}
int power(int a, int b, int c) {
int x = 1;
int y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % c;
}
y = (y * y) % c;
b = b / 2;
}
return x % c;
}
pair<vector<int>, int> encrypt(const string& msg, int q, int h, int g) {
vector<int> en_msg;
int k = gen_key(q);
int s = power(h, k, q);
int p = power(g, k, q);
for (char ch : msg) {
en_msg.push_back(s * int(ch));
}
cout << "g^k used: " << p << endl;
cout << "g^ak used: " << s << endl;
return make_pair(en_msg, p);
}
string decrypt(const vector<int>& en_msg, int p, int key, int q) {
string dr_msg;
int h = power(p, key, q);
for (int val : en_msg) {
dr_msg += char(val / h);
}
return dr_msg;
}
int main() {
string msg;
cout << "Enter the message to be encrypted: ";
getline(cin, msg);
int q, g;
cout << "Enter a large prime number q: ";
cin >> q;
cout << "Enter a primitive root g: ";
cin >> g;
int key = gen_key(q);
int h = power(g, key, q);
cout << "g used: " << g << endl;
cout << "g^a used: " << h << endl;
pair<vector<int>, int> encryption_result = encrypt(msg, q, h, g);
vector<int> en_msg = encryption_result.first;
int p = encryption_result.second;
cout << "Encrypted Message: ";
for (int val : en_msg) {
cout << val << " ";
}
cout << endl;
string dr_msg = decrypt(en_msg, p, key, q);
cout << "Decrypted Message: " << dr_msg << endl;
return 0;
}
SHA1
Python
import hashlib
input_str = input("Enter a string: ")
# Create a SHA-1 hash object
sha1 = hashlib.sha1()
# Update the hash object with the input string encoded as bytes
sha1.update(input_str.encode('utf-8'))
# Get the hexadecimal representation of the digest
hashed_str = sha1.hexdigest()
print("Hash value for", input_str,"is:", hashed_str)
Java
// SHA-1
import java.util.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main {
public static String encryptThisString(String input)
{
try {
// getInstance() method is called with algorithm SHA-1
MessageDigest md = MessageDigest.getInstance("SHA-1");
// digest() method is called to calculate message digest of the input string returned
as array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
// Add preceding 0s to make it 32 bit
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
// return the HashText
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException
{
Scanner sc= new Scanner(System.in);
System.out.println("Input Text: ");
String s1= sc.nextLine();
System.out.println("HashCode Generated by SHA-1 for: ");
System.out.println("\n" + s1 + " : " + encryptThisString(s1));
}
}
SHA+RSA (DSS) (Assign 6)
Code1 (P)
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
public class DigitalSignature {
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static byte[] generateDigitalSignature(byte[] hashValue, PrivateKey privateKey) throws
Exception {
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
signature.update(hashValue);
return signature.sign();
}
public static byte[] generateHash(String message) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
return digest.digest(message.getBytes());
}
public static boolean verifyDigitalSignature(byte[] hashValue, byte[] signature, PublicKey publicKey)
throws Exception {
Signature verifier = Signature.getInstance("SHA1withRSA");
verifier.initVerify(publicKey);
verifier.update(hashValue);
return verifier.verify(signature);
}
public static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02X", b));
}
return result.toString();
}
public static void main(String[] args) throws Exception {
KeyPair keyPair = generateKeyPair();
String message = "Cryptography and Network Security";
byte[] hashValue = generateHash(message);
byte[] digitalSignature = generateDigitalSignature(hashValue, keyPair.getPrivate());
System.out.println("Original Message: " + message);
System.out.println("Hash Value: " + bytesToHex(hashValue));
// System.out.println("Public Key (e): " + ((PublicKey) keyPair.getPublic()).getEncoded());
// System.out.println("Public Key (n): " + keyPair.getPublic().getAlgorithm());
// System.out.println("Private Key (d): " + ((PrivateKey) keyPair.getPrivate()).getEncoded());
System.out.println("Digital Signature: " + bytesToHex(digitalSignature));
boolean isVerified = verifyDigitalSignature(hashValue, digitalSignature, keyPair.getPublic());
System.out.println("Signature Verification: " + isVerified);
}
}
Code2
import java.math.BigInteger;
import java.security.*;
import java.util.Base64;
import javax.crypto.Cipher;
public class Main
{
public static String encryptThisString(String input)
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashText = no.toString(16);
while (hashText.length() < 32)
{
hashText = "0" + hashText;
}
return hashText;
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}
public static byte[] sign(String input, PrivateKey privateKey) throws Exception
{
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
signature.update(input.getBytes());
return signature.sign();
}
public static boolean verify(String input, byte[] signature, PublicKey publicKey) throws Exception
{
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(publicKey);
sig.update(input.getBytes());
return sig.verify(signature);
}
public static byte[] encrypt(String input, PublicKey publicKey) throws Exception
{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(input.getBytes());
}
public static String decrypt(byte[] encrypted, PrivateKey privateKey) throws Exception
{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encrypted);
return new String(decryptedBytes);
}
public static void main(String args[]) throws NoSuchAlgorithmException {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println("Message to be Encrypted and Signed: ");
String originalMessage = "GeeksForGeeks";
System.out.println("Original Message: " + originalMessage); // Print the original message
System.out.println("");
// Calculate SHA-1 hash of the original message
String hashedMessage = encryptThisString(originalMessage);
System.out.println("SHA-1 Hash: " + hashedMessage);
System.out.println("");
// Append the hash to the original message
String messageToEncryptAndSign = originalMessage + hashedMessage;
// Sign the entire message (message + hash) with the private key
byte[] signature = sign(messageToEncryptAndSign, privateKey);
System.out.println("Signature Generated: " + Base64.getEncoder().encodeToString(signature));
System.out.println("");
// Encrypt the entire message with the public key
byte[] encryptedData = encrypt(messageToEncryptAndSign, publicKey);
// Decrypt the ciphertext with the private key
String decryptedData = decrypt(encryptedData, privateKey);
System.out.println("Decrypted Data: " + decryptedData);
System.out.println("");
// Split the decrypted data to retrieve the original message and hash
int messageLength = originalMessage.length();
String decryptedMessage = decryptedData.substring(0, messageLength);
String decryptedHash = decryptedData.substring(messageLength);
// Verify the signature
String combinedMessage = decryptedMessage + decryptedHash;
boolean verified = verify(combinedMessage, signature, publicKey);
System.out.println("Signature Verified: " + verified);
System.out.println("");
// Compare the original message with the decrypted message
if (originalMessage.equals(decryptedMessage)) {
System.out.println("Original Message and Decrypted Message Match.");
} else {
System.out.println("Original Message and Decrypted Message Do Not Match.");
}
// Print the true message after decryption
System.out.println("True Message: " + decryptedMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
Man In Middle
#include <bits/stdc++.h>
using namespace std;
// Function to calculate (base^exponent) % mod using modular exponentiation
long long modPow(long long base, long long exponent, long long mod) {
if (mod == 1) return 0;
long long result = 1;
int a=pow(base,exponent);
result=a%mod;
return result;
}
int main() {
// Public keys are taken
// p is a prime number
// g is a primitive root of p
long long p, g;
cout << "Enter a prime number: ";
cin >> p;
cout << "Enter a number: ";
cin >> g;
// Generating private numbers for Alice, Bob, and Eve
long long alicePrivate, bobPrivate, eveAlicePrivate, eveBobPrivate;
cout << "Enter Alice's private number (a): ";
cin >> alicePrivate;
cout << "Enter Bob's private number (b): ";
cin >> bobPrivate;
cout << "Enter Eve's selected private number for Alice (c): ";
cin >> eveAlicePrivate;
cout << "Enter Eve's selected private number for Bob (d): ";
cin >> eveBobPrivate;
cout << endl;
// Generating public values
long long ga = modPow(g, alicePrivate, p);
long long gb = modPow(g, bobPrivate, p);
long long gea = modPow(g, eveAlicePrivate, p);
long long geb = modPow(g, eveBobPrivate, p);
cout << "Alice published (ga): " << ga << endl;
cout << "Bob published (gb): " << gb << endl;
cout << "Eve published value for Alice (gc): " << gea << endl;
cout << "Eve published value for Bob (gd): " << geb << endl;
// Computing the secret keys
long long sa = modPow(gea, alicePrivate, p);
long long sea = modPow(ga, eveAlicePrivate, p);
long long sb = modPow(geb, bobPrivate, p);
long long seb = modPow(gb, eveBobPrivate, p);
cout << "Alice computed (S1): " << sa << endl;
cout << "Eve computed key for Alice (S1): " << sea << endl;
cout << "Bob computed (S2): " << sb << endl;
cout << "Eve computed key for Bob (S2): " << seb << endl;
return 0;
}
RSA
Code1(p)
#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b)
{
if (b == 0)
{
return a;
}
return gcd(b, a % b);
}
long long int generatePublicKey(long long int phi)
{
long long int e = 2;
while (e < phi)
{
if (gcd(phi, e) == 1)
{
return e;
}
e++;
}
return e;
}
long long int generatePrivateKey(long long int e, long long int phi)
{
long long int d = 0;
while (1)
{
if ((d * e) % phi == 1)
{
return d;
}
d++;
}
return d;
}
long long int encryptMessage(long long int m, long long int e, long long int n)
{
long long int result = 1;
for (int i = 1; i <= e; i++)
{
result = result * m;
result = result % n;
}
return result % n;
}
long long int decryptMessage(long long int m, long long int d, long long int n)
{
long long int result = 1;
for (int i = 1; i <= d; i++)
{
result = result * m;
result = result % n;
}
return result % n;
}
int main()
{
int p1, p2;
cout << "Enter prime number p1: ";
cin >> p1;
cout << "Enter prime number p2: ";
cin >> p2;
long long int n = p1 * p2;
long long int phi = (p1 - 1) * (p2 - 1);
long long int e = generatePublicKey(phi);
long long int d = generatePrivateKey(e, phi);
cout << "Enter number want to encrypt: ";
int message;
cin >> message;
long long int cipherText = encryptMessage(message, e, n);
cout << "Cipher Text: " << cipherText << endl;
long long int originalMessage = decryptMessage(cipherText, d, n);
cout << "Decrypted number: " << originalMessage << endl;
return 0;
}
Code2
#include<iostream>
#include<math.h>
using namespace std;
// find gcd
int gcd(int a, int b) {
int t;
while(1) {
t= a%b;
if(t==0)
return b;
a = b;
b= t;
}
}
int main() {
//2 random prime numbers
double p = 13;
double q = 11;
double n=p*q;//calculate n
double track;
double phi= (p-1)*(q-1);//calculate phi
//public key
//e stands for encrypt
double e=7;
//for checking that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
while(e<phi) {
track = gcd(e,phi);
if(track==1)
break;
else
e++;
}
//private key
//d stands for decrypt
//choosing d such that it satisfies d*e = 1 mod phi
double d1=1/e;
double d=fmod(d1,phi);
double message = 9;
double c = pow(message,e); //encrypt the message
double m = pow(c,d);
c=fmod(c,n);
m=fmod(m,n);
cout<<"Original Message = "<<message;
cout<<"\n"<<"p = "<<p;
cout<<"\n"<<"q = "<<q;
cout<<"\n"<<"n = pq = "<<n;
cout<<"\n"<<"phi = "<<phi;
cout<<"\n"<<"e = "<<e;
cout<<"\n"<<"d = "<<d;
cout<<"\n"<<"Encrypted message = "<<c;
cout<<"\n"<<"Decrypted message = "<<m;
return 0;
}
OWN
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class InnovativeCipher {
public:
InnovativeCipher(int shift) : shift_(shift % 26) {}
string encrypt(const string &plaintext) {
string shiftedText = caesarShift(plaintext, shift_);
return convertToHex(shiftedText);
}
string decrypt(const string &ciphertext) {
string asciiText = convertFromHex(ciphertext);
return caesarShift(asciiText, 26 - shift_);
}
private:
string caesarShift(const string &text, int shift) {
string result = "";
for (char c : text) {
if (isalpha(c)) {
char base = isupper(c) ? 'A' : 'a';
c = (c - base + shift) % 26 + base;
}
result += c;
}
return result;
}
string convertToHex(const string &text) {
stringstream ss;
for (char c : text) {
ss << std::hex << std::setw(2) << std::setfill('0') << (int)(unsigned char)c;
}
return ss.str();
}
string convertFromHex(const string &hexText) {
string asciiText = "";
for (size_t i = 0; i < hexText.length(); i += 2) {
string byte = hexText.substr(i, 2);
char c = static_cast<char>(stoi(byte, nullptr, 16));
asciiText += c;
}
return asciiText;
}
int shift_;
};
int main() {
InnovativeCipher cipher(3); // Shift of 3
string plaintext = "Hello, World!";
string ciphertext = cipher.encrypt(plaintext);
cout << "Encrypted: " << ciphertext << endl;
string decryptedText = cipher.decrypt(ciphertext);
cout << "Decrypted: " << decryptedText << endl;
return 0;
}
Caesar Cipher
#include<stdio.h>
#include<ctype.h>
int main() {
char text[500], ch;
int key;
printf("Enter a message to encrypt: ");
scanf("%s", text);
printf("Enter the key: ");
scanf("%d", & key);
for (int i = 0; text[i] != '\0'; ++i) {
ch = text[i];
if (isalnum(ch)) {
//Lowercase characters.
if (islower(ch)) {
ch = (ch - 'a' + key) % 26 + 'a';
}
// Uppercase characters.
if (isupper(ch)) {
ch = (ch - 'A' + key) % 26 + 'A';
}
// Numbers.
if (isdigit(ch)) {
ch = (ch - '0' + key) % 10 + '0';
}
}
else {
printf("Invalid Message");
}
text[i] = ch;
}
printf("Encrypted message: %s \n", text);
// Decryption
printf("Enter a message to decrypt: ");
scanf("%s", text);
printf("Enter the key: ");
scanf("%d", & key);
for (int i = 0; text[i] != '\0'; ++i) {
ch = text[i];
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';
}
}
else {
printf("Invalid Message");
}
text[i] = ch;
}
printf("Decrypted message: %s \n", text);
return 0;
}
Monoalphabetic
#include <iostream>
#include <string>
using namespace std;
// Function to perform encryption using monoalphabetic cipher
void encrypt(string& plaintext, const string& key) {
int length = plaintext.length();
for (int i = 0; i < length; i++) {
if (isalpha(plaintext[i])) {
char originalChar = tolower(plaintext[i]);
int index = originalChar - 'a';
plaintext[i] = isupper(plaintext[i]) ? toupper(key[index]) : key[index];
}
}
}
// Function to perform decryption using monoalphabetic cipher
void decrypt(string& ciphertext, const string& key) {
int length = ciphertext.length();
for (int i = 0; i < length; i++) {
if (isalpha(ciphertext[i])) {
char encryptedChar = tolower(ciphertext[i]);
for (int j = 0; j < 26; j++) {
if (encryptedChar == tolower(key[j])) {
ciphertext[i] = isupper(ciphertext[i]) ? toupper('a' + j) : 'a' + j;
break;
}
}
}
}
}
int main() {
string key;
cout << "Enter the substitution key (26 letters in any order): ";
cin >> key;
string text;
cin.ignore(); // Clear the newline character from the buffer
cout << "Enter the text to be encrypted: ";
getline(cin, text);
// Encrypt the text
encrypt(text, key);
cout << "Encrypted text: " << text << endl;
// Decrypt the text
decrypt(text, key);
cout << "Decrypted text: " << text << endl;
return 0;
}
Vigenere
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void encrypt(char plaintext[], char key[]) {
int length = strlen(plaintext);
for (int i = 0; i < length; i++) {
if (isalpha(plaintext[i])) {
plaintext[i] = (toupper(plaintext[i]) - 'A' + toupper(key[i]) - 'A') % 26 + 'A';
}
}
}
void decrypt(char ciphertext[], char key[]) {
int length = strlen(ciphertext);
for (int i = 0; i < length; i++) {
if (isalpha(ciphertext[i])) {
int difference = ciphertext[i] - key[i];
if (difference < 0) {
difference += 26;
}
int decryptedChar = difference % 26;
printf("%d \n", decryptedChar);
ciphertext[i] = decryptedChar + 'A';
}
}
}
int main() {
char key[100];
printf("Enter the encryption key (same length as the text): ");
scanf("%s", key);
char text[100];
printf("Enter the text to be encrypted: ");
scanf(" %s", text);
if (strlen(text) != strlen(key)) {
printf("Error: Key length must match text length.\n");
return 1;
}
// Encrypt the text
encrypt(text, key);
printf("Encrypted text: %s\n", text);
// Decrypt the text
decrypt(text, key);
printf("Decrypted text: %s\n", text);
return 0;
}
Rail Fence
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void encrypt(char plaintext[], int rails) {
int length = strlen(plaintext);
char encryptedText[length];
int index = 0;
for (int i = 0; i < rails; i++) {
for (int j = i; j < length; j += rails) {
encryptedText[index++] = plaintext[j];
}
}
encryptedText[index] = '\0';
strcpy(plaintext, encryptedText);
}
void decrypt(char ciphertext[], int rails) {
int length = strlen(ciphertext);
char decryptedText[length];
int index = 0;
for (int i = 0; i < rails; i++) {
for (int j = i; j < length; j += rails) {
decryptedText[j] = ciphertext[index++];
}
}
decryptedText[length] = '\0';
strcpy(ciphertext, decryptedText);
}
int main() {
int rails;
printf("Enter the number of rails: ");
scanf("%d", &rails);
char text[100];
printf("Enter the text to be encrypted: ");
scanf(" %[^\n]", text);
encrypt(text, rails);
printf("Encrypted text: %s\n", text);
decrypt(text, rails);
printf("Decrypted text: %s\n", text);
return 0;
}
Columnar
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void encrypt(char plaintext[], char key[]) {
int textLength = strlen(plaintext);
int keyLength = strlen(key);
int rows = (textLength + keyLength - 1) / keyLength;
char matrix[rows][keyLength];
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < keyLength; j++) {
if (index < textLength) {
matrix[i][j] = plaintext[index++];
} else {
matrix[i][j] = 'X'; // Padding with 'X' if needed
}
}
}
for (int j = 0; j < keyLength; j++) {
for (int i = 0; i < rows; i++) {
printf("%c", matrix[i][key[j] - '1']);
}
}
printf("\n");
}
void decrypt(char ciphertext[], char key[]) {
int textLength = strlen(ciphertext);
int keyLength = strlen(key);
int rows = textLength / keyLength;
char matrix[rows][keyLength];
int index = 0;
for (int j = 0; j < keyLength; j++) {
for (int i = 0; i < rows; i++) {
matrix[i][key[j] - '1'] = ciphertext[index++];
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < keyLength; j++) {
printf("%c", matrix[i][j]);
}
}
printf("\n");
}
int main() {
char key[100];
printf("Enter the columnar transposition key (e.g., 2314): ");
scanf("%s", key);
char text[100];
printf("Enter the text to be encrypted/decrypted: ");
scanf(" %s", text);
int choice;
printf("Choose an operation:\n1. Encrypt\n2. Decrypt\n");
scanf("%d", &choice);
switch (choice) {
case 1:
encrypt(text, key);
break;
case 2:
decrypt(text, key);
break;
default:
printf("Invalid choice.\n");
return 1;
}
return 0;
}
Verman
#include <iostream>
#include <string>
using namespace std;
// Function to perform encryption using Vernam cipher
void encrypt(string& plaintext, const string& key) {
int length = plaintext.length();
for (int i = 0; i < length; i++) {
if (isalpha(plaintext[i])) {
plaintext[i] = (toupper(plaintext[i]) - 'A' + key[i] - 'A') % 26 + 'A';
}
}
}
// Function to perform decryption using Vernam cipher
void decrypt(string& ciphertext, const string& key) {
int length = ciphertext.length();
for (int i = 0; i < length; i++) {
if (isalpha(ciphertext[i])) {
int decryptedChar = (ciphertext[i] - key[i] + 26) % 26;
ciphertext[i] = decryptedChar + 'A';
}
}
}
int main() {
string key;
cout << "Enter the encryption key (same length as the text): ";
cin >> key;
cin.ignore(); // Clear the newline character from the buffer
string text;
cout << "Enter the text to be encrypted: ";
cin.ignore();
getline(cin, text);
if (text.length() != key.length()) {
cout << "Error: Key length must match text length." << endl;
return 1;
}
// Encrypt the text
encrypt(text, key);
cout << "Encrypted text: " << text << endl;
// Decrypt the text
decrypt(text, key);
cout << "Decrypted text: " << text << endl;
return 0;
}
Diffe-Hellman
#include <stdio.h>
#include <math.h>
int calculate(int base, int exponent, int modulus) {
int value = (int)pow(base, exponent);
int result = (value % modulus);
return result;
}
int main() {
int p, g, privateA, privateB, privateM;
printf("Enter prime number (p): ");
scanf("%d", &p);
printf("Enter primitive root (g): ");
scanf("%d", &g);
// Alice's private key
printf("Alice's private key (a): ");
scanf("%d", &privateA);
// Bob's private key
printf("Bob's private key (b): ");
scanf("%d", &privateB);
// Mallory's private key
printf("Mallory's private key (m): ");
scanf("%d", &privateM);
// Calculate public keys
int publicA = calculate(g, privateA, p);
int publicB = calculate(g, privateB, p);
printf("\nPublicly exchanged values:\n");
printf("Alice sends: %d\n", publicA);
printf("Bob sends: %d\n", publicB);
// Mallory (the attacker) intercepts the public values and generates a fake key
printf("\nMallory (the attacker) intercepts and generates a fake key:\n");
printf("Mallory intercepts Alice's public key: %d\n", publicA);
printf("Mallory intercepts Bob's public key: %d\n", publicB);
// Mallory sends her fake public key to Alice and Bob
int publicM = calculate(g, privateM, p);
printf("Mallory sends a fake public key to Alice and Bob: %d\n", publicM);
// Calculate the shared secret key for Alice and Mallory
int sharedSecretA = calculate(publicM, privateA, p);
printf("Shared Secret Key for Alice: %d (with Mallory)\n", sharedSecretA);
int sharedSecretMA = calculate(publicA, privateM, p);
printf("Shared Secret Key for Mallory: %d (with Alice)\n", sharedSecretMA);
// Calculate the shared secret key for Bob and Mallory
int sharedSecretB = calculate(publicM, privateB, p);
printf("Shared Secret Key for Bob: %d (with Mallory)\n", sharedSecretB);
int sharedSecretMB = calculate(publicB, privateM, p);
printf("Shared Secret Key for Mallory: %d (with Bob)\n", sharedSecretMB);
return 0;
}