C String Encryption: Caesar Cipher Guide

A common encryption method for C language strings is using a simple substitution algorithm, also known as the Caesar cipher.This method involves replacing each character in the string with a fixed offset to achieve encryption and decryption.

The specific steps are as follows:

  1. Specify an offset (such as 3) for replacing characters in a string.
  2. If it is a letter, it is replaced according to the shift amount, such as ‘A’ being replaced by ‘D’.
  3. If it is a number or other character, it will remain unchanged.
  4. The encrypted string is the replacement result.

The example code is shown below:

#include <stdio.h>
#include <string.h>

void encrypt(char* str, int offset) {
    int i;
    for (i = 0; i < strlen(str); i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') {
            str[i] = (str[i] - 'A' + offset) % 26 + 'A';
        } else if (str[i] >= 'a' && str[i] <= 'z') {
            str[i] = (str[i] - 'a' + offset) % 26 + 'a';
        }
    }
}

int main() {
    char str[100];
    int offset;

    printf("Enter a string: ");
    scanf("%s", str);

    printf("Enter an offset: ");
    scanf("%d", &offset);

    encrypt(str, offset);

    printf("Encrypted string: %s\n", str);

    return 0;
}

Please note that this simple substitution encryption method is not very secure and can be easily decrypted. For more secure encryption needs, consider using more complex encryption algorithms, such as the AES encryption algorithm.

bannerAds