首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C語言實現移位加密演算法:凱撒密碼與維吉尼亞密碼完整代碼

     編輯:C 語言問答

核心原理

**移位加密** 將明文字符按固定/可變位移量在字符集中循環平移。最經典為 **凱撒密碼** (固定位移) 與 **維吉尼亞密碼** (關鍵字決定逐字符位移)。

凱撒密碼實現 (僅字母、保留大小寫)

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

void caesar_encrypt(char *str, int shift) {
    shift %= 26;
    if (shift < 0) shift += 26;
    for (int i = 0; str[i]; i++) {
        if (isupper(str[i]))
            str[i] = 'A' + (str[i] - 'A' + shift) % 26;
        else if (islower(str[i]))
            str[i] = 'a' + (str[i] - 'a' + shift) % 26;
    }
}

void caesar_decrypt(char *str, int shift) {
    caesar_encrypt(str, 26 - shift);  // 反向位移即解密
}

int main() {
    char msg[] = "Hello, World!";
    int key = 3;
    printf("原文: %s\n", msg);
    caesar_encrypt(msg, key);
    printf("密文: %s\n", msg);
    caesar_decrypt(msg, key);
    printf("解密: %s\n", msg);
    return 0;
}

維吉尼亞密碼 (關鍵字加密)


void vigenere_encrypt(char *str, const char *key) {
    int keylen = strlen(key);
    int k = 0;
    for (int i = 0; str[i]; i++) {
        if (!isalpha(str[i])) continue;   // 非字母保留,不消耗關鍵字位
        int shift = toupper(key[k % keylen]) - 'A';
        if (isupper(str[i]))
            str[i] = 'A' + (str[i] - 'A' + shift) % 26;
        else
            str[i] = 'a' + (str[i] - 'a' + shift) % 26;
        k++;
    }
}

void vigenere_decrypt(char *str, const char *key) {
    int keylen = strlen(key);
    int k = 0;
    for (int i = 0; str[i]; i++) {
        if (!isalpha(str[i])) continue;
        int shift = toupper(key[k % keylen]) - 'A';
        if (isupper(str[i]))
            str[i] = 'A' + (str[i] - 'A' - shift + 26) % 26;
        else
            str[i] = 'a' + (str[i] - 'a' - shift + 26) % 26;
        k++;
    }
}

安全性警示

  • **極不安全**:字頻分析、已知明文攻擊可秒破。
  • **僅供教學/趣味**,生產環境**必須**使用 AES/ChaCha20 等現代認證加密 (搭配 TLS/NaCl/libsodium)。

工程化封裝建議


// 介面設計
typedef enum { CAESAR, VIGENERE } CipherType;

int cipher_process(char *data, size_t len,
                   CipherType type, int enc_dec,  // 1=encrypt, 0=decrypt
                   const void *key, size_t keylen); // key 為 int* 或 char*
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved