#include <stdio.h>
#include <string.h>
// Function to encrypt the message using Rail Fence Cipher
void railFenceEncrypt(char text[], int rails) {
int len = strlen(text);
char grid[rails][len];
int row = 0, col = 0;
int dir_down = 0; // flag to determine the direction (down or up)
// Initialize grid with empty spaces
for (int i = 0; i < rails; i++) {
for (int j = 0; j < len; j++) {
grid[i][j] = '\n';
}
}
// Fill the grid with the message in a zigzag pattern
for (int i = 0; i < len; i++) {
grid[row][col++] = text[i];
if (row == 0 || row == rails - 1) {
dir_down = !dir_down;
}
row += dir_down ? 1 : -1;
}
// Read the grid row by row to form the ciphertext
printf("Encrypted Text: ");
for (int i = 0; i < rails; i++) {
for (int j = 0; j < len; j++) {
if (grid[i][j] != '\n') {
printf("%c", grid[i][j]);
}
}
}
printf("\n");
}
int main() {
char text[] = "HELLO";
int rails = 3; // Number of rails (rows)
railFenceEncrypt(text, rails);
return 0;
}
#include <stdio.h>
#include <string.h>
// Function to encrypt the message using Columnar Transposition Cipher
void columnarEncrypt(char text[], char key[]) {
int len = strlen(text);
int keyLen = strlen(key);
int rows = (len + keyLen - 1) / keyLen; // Calculate the number of rows needed
char grid[rows][keyLen];
// Fill the grid with text, row by row
int k = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < keyLen; j++) {
if (k < len) {
grid[i][j] = text[k++];
} else {
grid[i][j] = 'X'; // Padding with 'X' if the grid is not full
}
}
}
// Sort the key to determine the column order
int order[keyLen];
for (int i = 0; i < keyLen; i++) {
order[i] = i;
}
// Sorting by key values
for (int i = 0; i < keyLen - 1; i++) {
for (int j = i + 1; j < keyLen; j++) {
if (key[order[i]] > key[order[j]]) {
int temp = order[i];
order[i] = order[j];
order[j] = temp;
}
}
}
// Print the encrypted message by reading columns in sorted order
printf("Encrypted Text: ");
for (int i = 0; i < keyLen; i++) {
for (int j = 0; j < rows; j++) {
printf("%c", grid[j][order[i]]);
}
}
printf("\n");
}
int main() {
char text[] = "HELLO";
char key[] = "ZEBRAS"; // Keyword to determine the column order
columnarEncrypt(text, key);
return 0;
}