Page 31
4.1 answer
1. // import required classes and package, if any
2. import java.util.Scanner;
3.
4. // create class CaesarCipherExample for encryption and d
ecryption
5. public class CaesarCipherExample
6. {
7. // ALPHABET string denotes alphabet from a-z
8. public static final String ALPHABET = "abcdefghijklmn
opqrstuvwxyz";
9.
10. // create encryptData() method for encrypting user input
string with given shift key
11. public static String encryptData(String inputStr, int shi
ftKey)
12. {
13. // convert inputStr into lower case
14. inputStr = inputStr.toLowerCase();
15.
16. // encryptStr to store encrypted data
17. String encryptStr = "";
18.
19. // use for loop for traversing each character of the input
string
20. for (int i = 0; i < inputStr.length(); i++)
21. {
22. // get position of each character of inputStr in ALPHAB
ET
23. int pos = ALPHABET.indexOf(inputStr.charAt(i));
24.
25. // get encrypted char for each char of inputStr
26. int encryptPos = (shiftKey + pos) % 26;
27. char encryptChar = ALPHABET.charAt(encryptPos);
28.
29. // add encrypted char to encrypted string
30. encryptStr += encryptChar;
31. }
32.
33. // return encrypted string
34. return encryptStr;
35. }
36.
37. // create decryptData() method for decrypting user input
string with given shift key
38. public static String decryptData(String inputStr, int shi
ftKey)
39. {
40. // convert inputStr into lower case
41. inputStr = inputStr.toLwowerCase();
42.
43. // decryptStr to store decrypted data
44. String decryptStr = "";
45.
46. // use for loop for traversing each character of the input
string
47. for (int i = 0; i < inputStr.length(); i++)
48. {
49.
50. // get position of each character of inputStr in ALPHAB
ET
51. int pos = ALPHABET.indexOf(inputStr.charAt(i));
52.
53. // get decrypted char for each char of inputStr
54. int decryptPos = (pos - shiftKey) % 26;
55.
56. // if decryptPos is negative
57. if (decryptPos < 0){
58. decryptPos = ALPHABET.length() + decryptPos;
59. }
60. char decryptChar = ALPHABET.charAt(decryptPos);
61.
62. // add decrypted char to decrypted string
63. decryptStr += decryptChar;
64. }
65. // return decrypted string
66. return decryptStr;
67. }
68.
69. // main() method start
70. public static void main(String[] args)
71. {
72. // create an instance of Scanner class
73. Scanner sc = new Scanner(System.in);
74.
75. // take input from the user
76. System.out.println("Enter a string for encryption using
Caesar Cipher: ");
77. String inputStr = sc.nextLine();
78.
79. System.out.println("Enter the value by which each char
acter in the plaintext message gets shifted: ");
80. int shiftKey = Integer.valueOf(sc.nextLine());
81.
82. System.out.println("Encrypted Data ===> "+encryptDa
ta(inputStr, shiftKey));
83. System.out.println("Decrypted Data ===> "+decryptDa
ta(encryptData(inputStr, shiftKey), shiftKey));
84.
85. // close Scanner class object
86. sc.close();
87. }
88. }
Page 35
4.1 answer
// C++ program Implementing One Time Pad Algorithm
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Method 1
// Returning encrypted text
string stringEncryption(string text, string key)
{
// Initializing cipherText
string cipherText = "";
// Initialize cipher array of key length
// which stores the sum of corresponding no.'s
// of plainText and key.
int cipher[key.length()];
for (int i = 0; i < key.length(); i++) {
cipher[i] = text.at(i) - 'A' + key.at(i) - 'A';
}
// If the sum is greater than 25
// subtract 26 from it
// and store that resulting value
for (int i = 0; i < key.length(); i++) {
if (cipher[i] > 25) {
cipher[i] = cipher[i] - 26;
}
}
// Converting the no.'s into integers
// Convert these integers to corresponding
// characters and add them up to cipherText
for (int i = 0; i < key.length(); i++) {
int x = cipher[i] + 'A';
cipherText += (char)x;
}
// Returning the cipherText
return cipherText;
}
// Method 2
// Returning plain text
static string stringDecryption(string s, string key)
{
// Initializing plain text
string plainText = "";
// Initializing integer array of key length
// which stores difference
// of corresponding no.'s of
// each character of cipherText and key
int plain[key.length()];
// Running for loop for each character
// subtracting and storing in the array
for (int i = 0; i < key.length(); i++) {
plain[i] = s.at(i) - 'A' - (key.at(i) - 'A');
}
// If the difference is less than 0
// add 26 and store it in the array.
for (int i = 0; i < key.length(); i++) {
if (plain[i] < 0) {
plain[i] = plain[i] + 26;
}
}
// Converting int to corresponding char
// add them up to plainText
for (int i = 0; i < key.length(); i++) {
int x = plain[i] + 'A';
plainText += (char)x;
}
// Returning plainText
return plainText;
}
// Method 3
// Main driver method
int main()
{
// Declaring plain text
string plainText = "Hello";
// Declaring key
string key = "MONEY";
// Converting plain text to toUpperCase
// function call to stringEncryption
// with plainText and key as parameters
for (int i = 0; i < plainText.length(); i++) {
// convert plaintext to uppercase
plainText[i] = toupper(plainText[i]);
}
for (int i = 0; i < key.length(); i++) {
// convert key to uppercase
key[i] = toupper(key[i]);
}
string encryptedText = stringEncryption(plainText, key);
// Printing cipher Text
cout << "Cipher Text - " << encryptedText << endl;
// Calling above method to stringDecryption
// with encryptedText and key as parameters
cout << "Message - " <<
stringDecryption(encryptedText, key);
return 0;
}
Page 43
4.1 answer
// C++ program to illustrate Rail Fence Cipher
// Encryption and Decryption
#include <bits/stdc++.h>
using namespace std;
// function to encrypt a message
string encryptRailFence(string text, int key)
{
// create the matrix to cipher plain text
// key = rows , length(text) = columns
char rail[key][(text.length())];
// filling the rail matrix to distinguish filled
// spaces from blank ones
for (int i=0; i < key; i++)
for (int j = 0; j < text.length(); j++)
rail[i][j] = '\n';
// to find the direction
bool dir_down = 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)
dir_down = !dir_down;
// fill the corresponding alphabet
rail[row][col++] = text[i];
// find the next row using direction flag
dir_down?row++ : row--;
}
//now we can construct the cipher using the rail matrix
string result;
for (int i=0; i < key; i++)
for (int j=0; j < text.length(); j++)
if (rail[i][j]!='\n')
result.push_back(rail[i][j]);
return result;
}
// This function receives cipher-text and key
// and returns the original text after decryption
string decryptRailFence(string cipher, int key)
{
// create the matrix to cipher plain text
// key = rows , length(text) = columns
char rail[key][cipher.length()];
// filling the rail matrix to distinguish filled
// spaces from blank ones
for (int i=0; i < key; i++)
for (int j=0; j < cipher.length(); j++)
rail[i][j] = '\n';
// to find the direction
bool dir_down;
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)
dir_down = true;
if (row == key-1)
dir_down = false;
// place the marker
rail[row][col++] = '*';
// find the next row using direction flag
dir_down?row++ : 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[index++];
// now read the matrix in zig-zag manner to construct
// the resultant text
string result;
row = 0, col = 0;
for (int i=0; i< cipher.length(); i++)
{
// check the direction of flow
if (row == 0)
dir_down = true;
if (row == key-1)
dir_down = false;
// place the marker
if (rail[row][col] != '*')
result.push_back(rail[row][col++]);
// find the next row using direction flag
dir_down?row++: row--;
}
return result;
}
//driver program to check the above functions
int main()
{
cout << encryptRailFence("attack at once", 2) << endl;
cout << encryptRailFence("GeeksforGeeks ", 3) << endl;
cout << encryptRailFence("defend the east wall", 3) <<
endl;
//Now decryption of the same cipher-text
cout << decryptRailFence("GsGsekfrek eoe",3) << endl;
cout << decryptRailFence("atc toctaka ne",2) << endl;
cout << decryptRailFence("dnhaweedtees alf tl",3) <<
endl;
return 0;
}
Page 46
4.1 answer
#include<bits/stdc++.h>
using namespace std;
// Key for Columnar Transposition
string const key = "HACK";
map<int,int> keyMap;
void setPermutationOrder()
{
// Add the permutation order into map
for(int i=0; i < key.length(); i++)
{
keyMap[key[i]] = i;
}
}
// Encryption
string encryptMessage(string msg)
{
int row,col,j;
string cipher = "";
/* calculate column of the matrix*/
col = key.length();
/* calculate Maximum row of the matrix*/
row = msg.length()/col;
if (msg.length() % col)
row += 1;
char matrix[row][col];
for (int i=0,k=0; i < row; i++)
{
for (int j=0; j<col; )
{
if(msg[k] == '\0')
{
/* Adding the padding character '_' */
matrix[i][j] = '_';
j++;
}
if( isalpha(msg[k]) || msg[k]==' ')
{
/* Adding only space and alphabet into matrix*/
matrix[i][j] = msg[k];
j++;
}
k++;
}
}
for (map<int,int>::iterator ii = keyMap.begin(); ii!
=keyMap.end(); ++ii)
{
j=ii->second;
// getting cipher text from matrix column wise using
permuted key
for (int i=0; i<row; i++)
{
if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i]
[j]=='_')
cipher += matrix[i][j];
}
}
return cipher;
}
// Decryption
string decryptMessage(string cipher)
{
/* calculate row and column for cipher Matrix */
int col = key.length();
int row = cipher.length()/col;
char cipherMat[row][col];
/* add character into matrix column wise */
for (int j=0,k=0; j<col; j++)
for (int i=0; i<row; i++)
cipherMat[i][j] = cipher[k++];
/* update the order of key for decryption */
int index = 0;
for( map<int,int>::iterator ii=keyMap.begin(); ii!
=keyMap.end(); ++ii)
ii->second = index++;
/* Arrange the matrix column wise according
to permutation order by adding into new matrix */
char decCipher[row][col];
map<int,int>::iterator ii=keyMap.begin();
int k = 0;
for (int l=0,j; key[l]!='\0'; k++)
{
j = keyMap[key[l++]];
for (int i=0; i<row; i++)
{
decCipher[i][k]=cipherMat[i][j];
}
}
/* getting Message using matrix */
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 for Geeks";
setPermutationOrder();
// Calling encryption function
string cipher = encryptMessage(msg);
cout << "Encrypted Message: " << cipher << endl;
// Calling Decryption function
cout << "Decrypted Message: " <<
decryptMessage(cipher) << endl;
return 0;
}