Practical No.
7
* Implement rail fence encryption technique to perform encryption of text
using C programming language
Program:-
#include <stdio.h>
#include <string.h>
// Function to encrypt plaintext using Rail Fence Cipher
void railFenceEncrypt(char *text, int rails) {
int len = strlen(text);
char rail[rails][len]; // Create an array of rails
memset(rail, '\n', sizeof(rail)); // Initialize the array with newline characters
int row = 0, col = 0;
int direction = 1; // 1 for moving down, -1 for moving up
// Fill the rail array in a zigzag pattern
for (int i = 0; i < len; i++) {
rail[row][col++] = text[i];
// Change direction when reaching the top or bottom rail
if (row == 0) {
direction = 1; // Move down
}
if (row == rails - 1) {
direction = -1; // Move up
}
// Move up or down
row += direction;
}
// Read the ciphertext row by row
printf("Encrypted Text: ");
for (int i = 0; i < rails; i++) {
for (int j = 0; j < len; j++) {
if (rail[i][j] != '\n') {
printf("%c", rail[i][j]);
}
}
}
printf("\n");
}
int main() {
char text[100];
int rails;
// Input plaintext and number of rails
printf("Enter the text to encrypt: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = 0; // Remove newline character from input
printf("Enter the number of rails: ");
scanf("%d", &rails);
// Encrypt the text
railFenceEncrypt(text, rails);
return 0;
}