CF Practicals Completed
CF Practicals Completed
CF Practicals Completed
CERTIFICATE
This is to certify that
As laid down in the regulation of University of Mumbai for the purpose of M.Sc. Computer
Date: 09 / 05 / 2022
Place: Bhiwandi
__________________________
Professor in Charge
___________________________ ______________________________
Signature of Head of Department Signature of External Examiner
Padmashri Annasaheb Jadhav Bharatiya Samaj Unnati Mandal’s
B. N. N. College of Arts, Science & Commerce, Bhiwandi
(Department of M.Sc. Computer Science)
CERTIFICATE
This is to certify that
Satisfactorily completed the Practical in Cyber & Information Security (Cryptography and Crypt
Analysis) As laid down in the regulation of University of Mumbai for the purpose of M.Sc.
Date: 09 / 05 / 2022
Place: Bhiwandi
__________________________
Professor in Charge
___________________________ ______________________________
Signature of Head of Department Signature of External Examiner
Padmashri Annasaheb Jadhav Bharatiya Samaj Unnati Mandal’s
B. N. N. College of Arts, Science & Commerce, Bhiwandi
(Department of M.Sc. Computer Science)
CERTIFICATE
This is to certify that
Satisfactorily completed the Practical in Cyber & Information Security (Cryptography and Crypt
Analysis) As laid down in the regulation of University of Mumbai for the purpose of M.Sc.
Date: 09 / 05 / 2022
Place: Bhiwandi
__________________________
Professor in Charge
___________________________ ______________________________
Signature of Head of Department Signature of External Examiner
INDEX
Sr. No PRATICAL NAME Remark / Signature
The Chinese remainder theorem is a theorem, which gives a unique solution tosimultaneous linear
congruence’s with co prime module. In its basic form, the Chinese remainder theorem will determine a
number pp that, when divided bysome given divisors, leaves given remainders.
Fermat’s little theorem states that if p is a prime number, then for any integera, the number a p – a is
an integer multiple of p.
Here p is a prime numberap ≡
a (mod p).
Special Case: If a is not divisible by p, Fermat’s little theorem is equivalent tothe .statement that a p-
1
-1 is an integer multiple of p.
ap-1 ≡ 1 (mod p)
OR
ap-1 % p = 1
Here a is not divisible by p.
PRACTICAL NO: 1
{
if (b == 0)
return a;
returngcd(b, a % b);
}
t = t1 - q *t2; t1 = t2;
t2 = t;
}
if (r1 == 1)
Minv[k] = t1;
if (Minv[k] < 0)
Minv[k] = Minv[k] + b[k];
}
int x = 0;
for (int k = 0; k < n; k++)
x += (a[k] * total * Minv[k]) / b[k];
return x;
}
{
int n = 4; // number ofequations int
a[n], b[n];
if (!check(b, n))
fprintf(stdout, "x = %d\n", evaluate(a, b, n));
else
fprintf(stdout, "The given equations has no solutions.\n");
return 0;
}
Input :
x=4(mod 10)
x=6(mod 13)
x=4(mod 7)
x=2(mod 11)
--------------------------------------------
Output :
x=81204
--------------------------------------------
else {
// If a and m are relatively prime, then
// modulo inverse is a^(m-2) mode mcout<<
"Modular multiplicative inverse is "
<<power(a, m - 2, m);
}
}
// To compute x^y under modulo m
int power(int x, unsigned int y, unsigned int m)
{
if (y == 0)
return 1;
int p = power(x, y / 2, m) %m; p = (p *
p) % m;
return (y % 2 == 0) ? p : (x * p) % m;
}
// Driver Program int
main()
{
int a = 3, m =11;
modInverse(a,m); return 0;
}
----------------------------------------------------------
Output :
Modular multiplicative inverse is 4
------------------------------------------------------------
Affine cipher:-
The Affine cipher is a type of mono alphabetic substitution cipher, wherein each letter in an alphabet is
mapped to its numeric equivalent, encrypted usinga simple mathematical function, and converted back
to a letter.
Rail fence:-
In the rail fence cipher, the plain text is written downwards and diagonally onsuccessive "rails" of an
imaginary fence, then moving up when the
bottom rail is reached. When the top rail is reached, the message is writtendownwards again until
the whole plaintext is written out.
Hill cipher:-
Hill cipheris s a polygraphic substitution cipher based on linear algebra. Invented by Lester S. Hill in
1929, it was the first polygraphic cipher in which itwas practical (though barely) to operate on more
than three symbols at once.
PRACTICAL NO:-2
Aim:- Write a program to implement the following:-
1. Affine Cipher
2. Rail Fence Technique
3. Simple Columnar Technique
4. Hill Cipher
1. Affine Cipher
#include iostream
#include string.h
#include stdlib.h
using namespace
std;
string encryptionMessage(string Msg)
{
string CTxt =""; int a = 3;int
b = 6;
for (int i = 0; i<Msg.length(); i++)
{
CTxt = CTxt + (char) ((((a * Msg[i]) + b) % 26) + 65);
}
return CTxt;
}
= 0;
for (int i = 0; i< 26; i++)
{
flag = (a * i) % 26; if (flag == 1)
{
a_inv = i;
}
}
for (inti = 0; i<CTxt.length(); i++)
{
Msg = Msg + (char) (((a_inv * ((CTxt[i] - b)) % 26)) + 65);
}
returnMsg;
}
int main(int argc, char **argv)
{
cout<< "Enter the message: "; string
message;
cin>> message;
cout<< "Message is :" << message;
cout<< "\nEncrypted Message is : " <<encryptionMessage(message);cout<< "\nDecrypted Message is: "
<<decryptionMessage(encryptionMessage(message));
}
--------------------------------------------------------------
Output:
++j) if(railMatrix[i][j]
!= '\n')
printf("%c", railMatrix[i][j]);
}
void decryptMsg(char enMsg[], int key){
int msgLen = strlen(enMsg), i, j, k = -1, row = 0, col =0, m = 0; char
railMatrix[key][msgLen];
for(i = 0; i < key; ++i) for(j = 0; j <
msgLen;
++j) railMatrix[i][j] ='\n';
for(i = 0; i < msgLen; ++i){
railMatrix[row][col++] = '*';
if(row == 0 || row == key-1) k= k * (-1);
row = row + k;
}
if(railMatrix[i][j] == '*')railMatrix[i][j] =
enMsg[m++];
row = col =0; k = -1;
printf("\nDecrypted Message: ");
char matrix[row][col];
for (int i=0,k=0; i < row; i++)
{
for (int j=0; j<col; )
{
if(msg[k] == '\0')
{
matrix[i][j] =
'_'; j++;
}
if( isalpha(msg[k]) || msg[k]==' ')
{
{
decCipher[i][k]=cipherMat[i][j];
}
}
/* getting Message usingmatrix */ string msg =
"";
for (int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
if(decCipher[i][j] !='_') msg +=
decCipher[i][j];
}
}
return msg;
}
// Driver Program int
main(void)
{
/* message */
string msg = "Geeks forGeeks";
setPermutationOrder();
// Calling encryption function
string cipher = encryptMessage(msg);
cout << "Encrypted Message: " << cipher << endl;
----------------------------------------------------
Output:-
}
int main(int argc, char **argv)
{
int l, i, j;int temp1; int
k[3][3];
int p[3][1];
int c[3][1];
char ch;cout
<< "\nThis cipher has a key of length 9. ie. a 3*3 matrix.\nEnter the 9character key.
";
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%c", &ch);
if (65 <= ch && ch <=91) k[i][j] = (int)
ch
% 65;
else
k[i][j] = (int) ch % 97;
}
}
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
cout << k[i][j] << " ";
}
cout << endl;
}
cout << "\nEnter the length of string to be encoded(withoutspaces). "; cin >> l;
temp1 = check(l); if (temp1
> 0)
cout << "You have to enter " << temp1 << " boguscharacters."; char pi[l + temp1];
cout << "\nEnter the string. "; for (i = -1; i < l
+temp1; ++i)
{
cin >> pi[i];
}
int temp2 = l;
int n = (l + temp1) /3; int temp3;
int flag =0; int count;
cout << "\n\nThe encoded cipheris : "; while (n > 0)
{
count = 0;
for (i = flag; i < flag + 3; ++i)
{
if (65 <= pi[i] && pi[i] <=91) temp3 = (int)
pi[i]
% 65;
else
temp3 = (int) pi[i] %97; p[count][0] =
temp3; count = count
+ 1;
}
int k1;
for (i = 0; i < 3;
++i) c[i][0] = 0;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 1; ++j)
{
for (k1 = 0; k1 < 3; ++k1)c[i][j] += k[i][k1] *
p[k1][j];
}
}
for (i = 0; i < 3; ++i)
{
c[i][0] = c[i][0] % 26;
printf("%c ", (char) (c[i][0] + 65));
}
n = n - 1;
flag = flag + 3;
}
}
Output:-
--------------------------------------------------------------------
This cipher has a key of length 9. ie. a 3*3matrix. Enter the 9
character key.
DharHingu3 7 0
17 7 8
13 6 20
RSA algorithm is a popular exponentiation in a finite field over integers includingprime numbers.
The integers used by this method are sufficiently large making it difficult to solve.
There are two sets of keys in this algorithm: private key and public key.
You will have to go through the following steps to work on RSA algorithm −
N=p*q
Here, let N be the specified large number.
Encryption Formula
Consider a sender who sends the plain text message to someone whose public key is(n,e). To encrypt the plain
text message in the given scenario, use the following syntax −
C = Pe mod n Decryption
Formula
The decryption process is very straightforward and includes analytics for calculationin a systematic approach.
Considering receiver C has the private key d, the result modulus will be calculated as −
Plaintext = Cd mod n
PRACTICAL NO:- 3
Aim:- Write a program to implement the RSA Algorithm to perform encryptionand decryption.
#include<stdio.h>
#include<math.h>
// Returns gcd of a and b int gcd(int a, int h)
{
}
// Code to demonstrate RSAalgorithm int main()
{
= 2;
break
; else
e++;
}
// Private key (d stands for decrypt)
// Encryption c = (msg ^ e)
% n double c = pow(msg,e);
c = fmod(c, n);
printf("\nEncrypted data = %lf", c);
// Decryption m = (c ^ d)
--------------------------------------------------------
Output :
Message data = 12.000000Encrypted
data = 3.000000Original Message Sent =
12.000000
-------------------------------------------------
Miller-Rabin Algorithm:-
Miller–Rabin primality test or Rabin–Miller primality test is a primality test: analgorithm which
determines whether a given number is likely to be prime, similar to the Fermat primality test and the
Solovay–Strassen primality test.
1 ) Miller-Rabin Algorithm
// C++ program Miller-Rabin primalitytest
#include <bits/stdc++.h>
using namespace std;
// Utility function to do modular exponentiation.
// It returns (x^y) % p
res = (res*x) % p;
return res;
}
// This function is called for all k trials. It returns
// probably prime.
{
// Pick a random number in [2..n-2]
if (x == 1 || x == n-1)return true;
// Keep squaring x while one of the following doesn't
// happen
while (d != n-1)
x = (x * x) %n; d *= 2;
if (x == 1) returnfalse; if (x == n-1)
return true;
// Corner cases
while (d % 2 == 0)
d /= 2;
}
// Driver program int
main()
{
int k = 4; // Number of iterations cout << "All primes smaller
than 100: \n"; for (int n = 1; n < 100; n++)
if (isPrime(n, k)) cout << n
return 0;
}
-------------------------------------------------------
Output:-
All primes smaller than 100 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97
---------------------------------------------------------
/* exponent = exponent/2
*/ exponent = exponent >>1;
/* base = base * base */
base = (base * base) % modulus;
}
return result;
}
/* method to return prime divisor for n */ long long int
PollardRho(long long int n)
{
/* initialize random seed
*/ srand (time(NULL));
*/ while (d==1)
{
/* Tortoise Move: x(i+1) = f(x(i)) */
x = (modular_pow(x, 2, n) + c + n)%n;
+ c + n)%n;
/* driver function
*/ int main()
{
long long int n = 10967535067; printf("One of the divisors for
%lld is
%lld.", n, PollardRho(n));return 0;
}
-----------------------------------------------
Output:-
Prime factors of 1403 are 61 23
-----------------------------------------------
ElGamal Crytosystem:-
ElGamal encryption system is an asymmetric key encryption algorithm for public-key cryptography
which is based on the Diffie–Hellman key exchange. Itwas described by Taher Elgamal in 1985.
ElGamal Cryptosystem ElGamal encryption is used in the free GNU Privacy Guard software, recent
versions of PGP, and other cryptosystems. The Digital Signature Algorithm (DSA) is a variant of the
ElGamal signature scheme, which should not be confused with ElGamal encryption.
PRACTICAL NO:-5
Aim:- Write a program to implement the ElGamel Cryptosystem togenerate keys to perform
encryption and decryption.
#import random
from math import powa =
random.randint(2, 10) def gcd(a, b):
if a < b:
return gcd(b,a) elif a % b == 0:
returnb; else:
return gcd(b, a % b)
y=a
while b > 0:
if b % 2 == 0:
x = (x * y) %c; y = (y * y)
% c b =int(b / 2)
return x % c
return en_msg, p
def decrypt(en_msg, p,key, q): dr_msg = []
h = power(p, key, q)
for i in range(0, len(en_msg)):
dr_msg.append(chr(int(en_msg[i]/h)))
return dr_msg
# Driver code def
main():
msg = 'encryption' print("Original Message :",
msg)
q = random.randint(pow(10, 20), pow(10, 50)) g = random.randint(2,
q)
key = gen_key(q)# Private key forreceiver h = power(g,
key, q) print("g used : ", g)
print("g^a used : ", h)
en_msg, p = encrypt(msg, q, h, g) dr_msg =
decrypt(en_msg, p,key, q) dmsg = ''.join(dr_msg)
print("Decrypted Message :", dmsg);
if _name_ == '_main_': main()
-------------------------------------------------------------------------------------------------
Output:-
Original Message : encryptiong used :
5860696954522417707188952371547944035333315907890 g^a
used : 4711309755639364289552454834506215144653958055252 g^k
used : 12475188089503227615789015740709091911412567126782
g^ak used : 39448787632167136161153337226654906357756740068295
Decrypted Message : encryption
-----------------------------------------------------------------------------------------------------
Diffie–Hellman key exchange:-
Diffie–Hellman key exchange is a method of securely exchanging cryptographic keysover a public
channel and was one of the first public-key protocols as conceived
by Ralph Merkle and named after Whitfield Diffie and Martin Hellman. DH is one of the earliest
practical examples of public key exchange implemented within the field of cryptography. Published in
1976 by Diffie and Hellman, this is the earliest publiclyknown work that proposed the idea of a private
key and a corresponding public key.
Traditionally, secure encrypted communication between two parties required that they first exchange
keys by some secure physical means, such as paper key lists transported by a trusted courier. The
Diffie–Hellman key exchange method allows two parties that have no prior knowledge of each other
to jointly establish a sharedsecret key over an insecure channel. This key can then be used to encrypt
subsequent communications using a symmetric key cipher.
PRACTICAL NO: - 6
Aim:-Write a program to implement the Diffie-Hellman Key Agreementalgorithm to generate
symmetric keys.
#include<stdio.h>
#include<math.h>
// Power function to return value of a ^ b mod P
long long int power(long long int a, long long int b, long long int P)
{
if (b == 1) returna; else
return (((long long int)pow(a, b)) % P);
}
//Driver program intmain()
{
long long int P, G, x, a, y, b, ka, kb;
// Both the persons will be agreed upon the
G = 9;
%lld\n\n", G);
// Alice will choose the privatekey a a = 4;
// a is the chosen private key printf("The private key a for Alice :
%lld\n", a); x = power(G, a, P); // gets thegenerated key
// Bob will choose the private key b b = 3;
// b is the chosenprivate key
printf("The private key b for Bob :
%lld\n\n", b); y = power(G, b, P);
// of keys
ka = power(y, a, P); // Secret key for Alice kb = power(x, b, P); // Secret key
for Bob
printf("Secret key for the Alice is :%lld\n", ka); printf("Secret Key for the Bob is : %lld\n", kb);
return 0;
}
----------------------------------------------
Output:-
The value of P :
23 The value ofG : 9
The MD5 hash function was originally designed for use as a secure cryptographic hash algorithm for
authenticating digital signatures. But MD5 has been deprecated for uses other than as a
noncryptographic checksum to verify data integrity and detect unintentional data corruption. The MD5
message-digest hashing algorithm processes data in 512-bit strings, broken down into 16 words
composed of 32 bits each. The output from MD5 is a 128-bit message-digest value.
Computation of the MD5 digest value is performed in separate stages that process each 512-bit block of
data along with the value computed in the preceding stage. The first stage begins with the message-
digest values initialized using consecutive hexadecimal numerical values. Each stage includes four
message-digest passes, which manipulate values in the current data block and values processed from the
previous block. The final value computed from the last block becomes the MD5 digest for that block.
This Algorithms are initialize in static method called getInstance(). After selecting the algorithm it
calculate the digest value and return the results inbyte array.
BigInteger class is used, which converts the resultant byte array into its sign-magnitude
representation.
This representation converts into hex format to get the MessageDigest
PRACTICAL NO:-7
Aim: - Write a program to implement the MD5 algorithm compute the messagedigest.
import java.math.BigInteger;
import java.security.MessageDigest; import
java.security.NoSuchAlgorithmException;public class MD5
{
public static String getMd5(String input)
{
try
// Static getInstance method is called with hashingMD5 MessageDigest md =
MessageDigest.getInstance("MD5");
// digest() method is called to calculate message digest
// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());
{
throw new RuntimeException(e);
}
}
// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException
String s = "GeeksForGeeks";
System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
}
}
---------------------------------------------------------------------------------------------------------
Output:-
Your HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6
---------------------------------------------------------------------------------------------------------
DES is a block cipher, and encrypts data in blocks of size of 64 bit each, means 64 bits of plain text goes as the input to
DES, which produces 64 bits ofcipher text. The same algorithm and key are used for encryption and decryption, with minor
differences. The key length is 56 bits.
We have mention that DES uses a 56 bit key. Actually, the initial key consistsof 64 bits. However, before the DES
process even starts, every 8th bit of the key is discarded to produce a 56 bit key. That is bit position 8, 16, 24, 32, 40,
48, 56 and 64 are discarded.
Thus, the discarding of every 8th bit of the key produces a 56-bit key from theoriginal 64-bit key.
DES is based on the two fundamental attributes of cryptography: substitution (also called as confusion) and
transposition (also called as diffusion). DES consists of 16 steps, each of which is called as a round. Each round performs
the steps of substitution and transposition. Let us now discuss the broad-levelsteps in DES.
In the first step, the 64 bit plain text block is handed over to an initialPermutation (IP) function.
Next the initial permutation (IP) produces two halves of the permuted block;says Left Plain Text (LPT) and Right Plain Text (RPT).
In the end, LPT and RPT are rejoined and a Final Permutation (FP) isperformed on the combined block
For example, it says that the IP replaces the first bit of the original plain text block with the 58th bit of the original plain text, the second bit with the 50th bit
of the original plain text block and so on.
As we have noted after IP done, the resulting 64-bit permuted text block is divided into two half blocks. Each half block consists of 32 bits, and
each ofthe 16 rounds, in turn, consists of the broad level steps :-
We have noted initial 64-bit key is transformed into a 56-bit key by discarding every 8th bit of the initial key. Thus, for
each a 56-bit key is available. From this56-bit key, a different 48-bit Sub Key is generated during each round using a
process called as key transformation. For this the 56 bit key is divided into two halves, each of 28 bits. These halves are
circularly shifted left by one or two positions, depending on the round.
For example, if the round number 1, 2, 9 or 16 the shift is done by only position for other rounds, the circular shift is done by
two positions.
After an appropriate shift, 48 of the 56 bit are selected. for selecting 48 of the 56 bits the table show in figure given below.
For instance, after the shift, bit number 14 moves on the first position, bit number 17 moves on the second position and so
on. If we observe the table carefully, we will realize that it contains only 48 bit positions. Bit number 18 is discarded (we
will not find it inthe table), like 7 others, to reduce a 56-bit key to a 48-bit key. Since the key transformation process
involves permutation as well as selection of a 48-bit sub set of the original 56-bit key it is called Compression Permutation.
Because of this compression permutation technique, a different subset of keybits is used in each round. That’s make DES
not easy to crack.
Recall that after initial permutation, we had two 32-bit plain text areas called asLeft Plain Text(LPT) and Right Plain
Text(RPT). During the expansion permutation, the RPT is expanded from 32 bits to 48 bits. Bits are permuted as well hence
called as expansion permutation. This happens as the 32 bit RPT isdivided into 8 blocks, with each block consisting of 4
bits. Then, each 4 bit block of the previous step is then expanded to a corresponding 6 bit block, i.e., per 4 bit block, 2 more
bits are added.
This process results into expansion as well as permutation of the input bit while creating output. Key transformation process
compresses the 56-bit key to 48 bits. Then the expansion permutation process expands the 32-bit RPT to 48-bits. Now the
48-bit key is XOR with 48-bit RPT and resulting output is givento the next step, which is the S-Box substitution.
PRACTICAL NO:-8
Aim:- Write a program to implement different processes of DES algorithm like (i) Initial
Permutation process of DES algorithm, (ii) Generate Keys for DES algorithm, (iii) S-Box
substitution for DES algorithm.
#include
<bits/stdc++.h> usingnamespace std;
string hex2bin(string s)
{
// hexadecimal to binary conversion
unordered_map<char, string>mp; mp['0'] = "0000";
mp['1'] = "0001";
mp['2'] = "0010";
mp['3'] = "0011";
mp['4'] = "0100";
mp['5'] = "0101";
mp['6'] = "0110";
mp['7'] = "0111";
mp['8'] = "1000";
mp['9'] = "1001";
mp['A'] = "1010";
mp['B'] = "1011";
mp['C'] = "1100";
mp['D'] = "1101";
mp['E'] = "1110";
mp['F'] = "1111";
string bin = "";
for (int i = 0; i < s.size();i++) { bin +=
mp[s[i]];
}
return bin;
}
string bin2hex(string s)
{
// binary to hexadecimalconversion
unordered_map<string, string>mp; mp["0000"] = "0";
mp["0001"] = "1";
mp["0010"] = "2";
mp["0011"] = "3";
mp["0100"] = "4";
mp["0101"] = "5";
mp["0110"] = "6";
mp["0111"] = "7";
mp["1000"] = "8";
mp["1001"] = "9";
mp["1010"] = "A";
mp["1011"] = "B";
mp["1100"] = "C";
mp["1101"] = "D";
mp["1110"] = "E";
mp["1111"] = "F";
+ 2]; ch +=
s[i + 3]; hex
+= mp[ch];
}
return hex;
}
string permute(string k, int* arr, int n)
{
string per = "";
for (int i = 0; i < n;i++) { per +=
k[arr[i] - 1];
}
return per;
}
string shift_left(string k, int shifts)
{
string s = "";
for (int i = 0; i < shifts; i++) { for (int j = 1;
j <28; j++) {
s += k[j];
}
s += k[0];
k = s; s= "";
}
return k;
}
string xor_(string a, string b)
{
string ans = "";
for (int i = 0; i < a.size();i++) { if (a[i] ==
b[i]) {
ans += "0";
}
else
{
ans += "1";
}
}
return ans;
}
string encrypt(string pt, vector<string> rkb, vector<string> rk)
{
// Hexadecimal to binary
pt = hex2bin(pt);
// Initial Permutation Table
int initial_perm[64] = { 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 };
// Initial Permutation
pt = permute(pt, initial_perm, 64);
cout << "After initial permutation: " << bin2hex(pt) << endl;
// Splitting
string left = pt.substr(0,32); string right =
pt.substr(32, 32);
cout << "After splitting: L0=" << bin2hex(left)
<< " R0=" << bin2hex(right) << endl;
// Expansion D-box Table
int exp_d[48] = { 32, 1, 2, 3, 4, 5, 4, 5,
6, 7, 8, 9, 8, 9, 10, 11,
12, 13, 12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21, 20, 21,
22, 23, 24, 25, 24, 25, 26, 27,
// Expansion D-box
string right_expanded = permute(right, exp_d, 48);
s[i][row][col]; op +=
char(val / 8 + '0'); val
= val % 8;
op += char(val / 4 + '0'); val = val % 4;
op += char(val / 2 + '0'); val = val % 2;
op += char(val + '0');
}
// Straight D-box
op = permute(op, per, 32);
// XOR left and op x = xor_(op,
left); left = x;
// Swapperif (i != 15)
{
swap(left, right);
}
cout << "Round " << i + 1 << " " << bin2hex(left) << " "
<< bin2hex(right) << " " << rk[i] << endl;
}
// Combination
string combine = left + right;
// Splitting
string left = key.substr(0,28); string right =
key.substr(28, 28);
vector<string> rkb; // rkb for RoundKeys in binary vector<string> rk; // rk for
RoundKeys inhexadecimal
for (int i = 0; i < 16; i++)
{
// Shifting
left = shift_left(left, shift_table[i]);
// Combining
string combine = left + right;
// Key Compression
string RoundKey = permute(combine, key_comp, 48);
rkb.push_back(RoundKey);rk.push_back(bin2hex(RoundKey));
}
cout << "\nEncryption:\n\n";string cipher =
encrypt(pt, rkb, rk);
cout << "\nCipher Text: " << cipher <<endl; cout <<
"\nDecryption\n\n"; reverse(rkb.begin(), rkb.end());
reverse(rk.begin(), rk.end()); string text = encrypt(cipher,
rkb,
Output:
-----------------------------------------------------------------------------------------------------------
Encryption:
Decryption
------------------------------------------------------------------------------------------------