C_C++

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

고니자니 2023. 11. 19. 13:46
반응형

C언어를 이용한 다양한 암호화 방법이 있습니다.

여기서는 일반 텍스트의 각 문자가 고정된 위치만큼 이동되는 간단한 Caesar 암호화 방법을 이용해서 입력 받은 문자열을 암호화하고 다시 복호화 하는 C언어 코드를 설명합니다.

 

shift로 사용되는 변수는 문자열이 이동되는 크기를 나타내는 값으로 임의의 값으로 수정할 수 있습니다.

영문자만  shift 연산을 수행합니다.

#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;
}

(Output)

Enter message: hello123 HELLO987

Encrypted message: rovvy123 ROVVY987
Decrypted message: hello123 HELLO987

(C언어) Caesar 암호화, 복호화

728x90
반응형