✅ 목표 (Goal)

시저, 카이사르 암호화를 코딩해보자.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

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

void decrypt(char* text, int shift) {
    for (int i = 0; text[i] != '\\0'; ++i) {
        if (text[i] >= 'a' && text[i] <= 'z') {
            text[i] = (text[i] - 'a' - shift + 26) % 26 + 'a';
        }
        else if (text[i] >= 'A' && text[i] <= 'Z') {
            text[i] = (text[i] - 'A' - shift + 26) % 26 + 'A';
        }
    }
}

int main() {
    char message[100];
    int shift = 10;

    // Input message
    printf("Enter message: ");
    fgets(message, sizeof(message), stdin);

    // Input shift value
    // printf("Enter shift value: ");
    // scanf("%d", &shift);

    // Encrypt the message
    encrypt(message, shift);

    // Display the encrypted message
    printf("\\nEncrypted message: %s", message);

    // Decrypt the message
    decrypt(message, shift);

    // Display the decrypted message
    printf("Decrypted message: %s\\n", message);

    return 0;
}
//출처: <https://gonyzany.tistory.com/642> [고니의 코딩노트:티스토리]

실제로 필드에서 사용할 일은 없고, 그냥 문자열 연습용

image.png

✅ 참조 (Ref.)

▼ (C언어) Caesar (시저, 카이사르) 암호화 복호화

https://gonyzany.tistory.com/642