Program:
Rail Fence Cipher:
#include <stdio.h>#include <string.h>#include <stdlib.h>main(){int i, j, len, rails, count, code[100][1000];char str[1000];printf("Enter a Secret Message\n");gets(str);len = strlen(str);printf("Enter number of rails\n");scanf("%d", &rails);for (i = 0; i < rails; i++){for (j = 0; j < len; j++){code[i][j] = 0;}}count = 0;j = 0;while (j < len){if (count % 2 == 0){for (i = 0; i < rails; i++){// strcpy(code[i][j],str[j]);code[i][j] = (int)str[j];j++;}}else{for (i = rails - 2; i > 0; i--){code[i][j] = (int)str[j];j++;}}count++;}for (i = 0; i < rails; i++){for (j = 0; j < len; j++){if (code[i][j] != 0)printf("%c", code[i][j]);}}printf("\n");}
Columnar Transposition Cipher:
#include <bits/stdc++.h>using namespace std;string const key = "HACK";map<int, int> keyMap;void setPermutationOrder(){for (int i = 0; i < key.length(); i++){keyMap[key[i]] = i;}}string encryptMessage(string msg){int row, col, j;string cipher = "";col = key.length();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'){matrix[i][j] = '_';j++;}if (isalpha(msg[k]) || msg[k] == ' '){matrix[i][j] = msg[k];j++;}k++;}}for (map<int, int>::iterator ii = keyMap.begin(); ii != keyMap.end(); ++ii){j = ii->second;for (int i = 0; i < row; i++){if (isalpha(matrix[i][j]) || matrix[i][j] == ' ' || matrix[i][j] == '_')cipher += matrix[i][j];}}return cipher;}string decryptMessage(string cipher){int col = key.length();int row = cipher.length() / col;char cipherMat[row][col];for (int j = 0, k = 0; j < col; j++)for (int i = 0; i < row; i++)cipherMat[i][j] = cipher[k++];int index = 0;for (map<int, int>::iterator ii = keyMap.begin(); ii != keyMap.end(); ++ii)ii->second = index++;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];}}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;}int main(void){string msg = "Geeks for Geeks";setPermutationOrder();string cipher = encryptMessage(msg);cout << "Encrypted Message: " << cipher << endl;cout << "Decrypted Message: " << decryptMessage(cipher) << endl;return 0;}
Output:
Rail Fence:
Columnar Transposition Cipher:
0 Comments