Implement Caesar cipher encryption-decryption.

 Implement Caesar cipher encryption-decryption.

About Caesar cipher:

The Caesar Cipher is one of the simplest and oldest methods of encrypting messages, named after Julius Caesar, who reportedly used it to protect his military communications. This technique involves shifting the letters of the alphabet by a fixed number of places. For example, with a shift of three, the letter ‘A’ becomes ‘D’, ‘B’ becomes ‘E’, and so on. Despite its simplicity, the Caesar Cipher formed the groundwork for modern cryptographic techniques. In this article, we’ll explore how the Caesar Cipher works, its significance, and its impact on the development of cryptography with its advantages and disadvantages.

Cryptography Algorithm For the Caesar Cipher

  • Thus to cipher a given text we need an integer value, known as a shift which indicates the number of positions each letter of the text has been moved down.
  • The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of a letter by a shift n can be described mathematically as.
  • For example, if the shift is 3, then the letter A would be replaced by the letter D, B would become E, C would become F, and so on. The alphabet is wrapped around so that after Z, it starts back at A.
  • Here is an example of how to use the Caesar cipher to encrypt the message “HELLO” with a shift of 3:

How It Works:

1.      Choose a shift value (key), which determines how many positions each letter will move.

2.      Replace each letter in the plaintext with the letter that appears "shift value" places after it in the alphabet.

3.      If shifting goes past 'Z', it wraps around to the beginning of the alphabet.

4.      The same shift is applied to decrypt the message by shifting in the opposite direction.

Example:

 

Encryption

Plaintext: `HELLO`

Shift = 3

Replace each letter:

H → K

E → H

L → O

L → O

O → R

Ciphertext: `KHOOR`

 

Decryption

Ciphertext: KHOOR

Shift = 3 (reverse shift by subtracting)

K → H

H → E

O → L

O → L

R → O

Plaintext: HELLO

 

C Code:

#include <stdio.h>

#include <ctype.h>

 #define SHIFT 3

 

char caesar_encrypt(char c) {

    if (!isalpha(c)) return c;

    char base = islower(c) ? 'a' : 'A';

    return (c - base + SHIFT) % 26 + base;

}

 

char caesar_decrypt(char c) {

    if (!isalpha(c)) return c;

    char base = islower(c) ? 'a' : 'A';

    return (c - base - SHIFT + 26) % 26 + base;

}

 

int main() {

    char input[100];

    printf("Enter a string: ");

    fgets(input, sizeof(input), stdin);

    printf("Encrypted: ");

    for (int i = 0; input[i] != '\0'; i++) {

        printf("%c", caesar_encrypt(input[i]));

    }

    printf("\nDecrypted: ");

    for (int i = 0; input[i] != '\0'; i++) {

        printf("%c", caesar_decrypt(input[i]));

    }

    return 0;

}

 

Input/Output:



Comments