凯撒密码用c语言实现

凯撒密码是历史上最简单的加密方式之一,它基于一种替换方法,即将明文中的每个字母都替换成它之后的第 N 个字母。下面是一个简单的 C 语言实现:

复制代码
#include <stdio.h>
#include <string.h>

// 加密函数,plaintext 为明文,key 为加密密钥
void encrypt(char plaintext[], int key) {
    int len = strlen(plaintext);
    for (int i = 0; i < len; i++) {
        if (plaintext[i] >= 'a' && plaintext[i] <= 'z') {
            // 处理小写字母
            plaintext[i] = (plaintext[i] - 'a' + key) % 26 + 'a';
        } else if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') {
            // 处理大写字母
            plaintext[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
        }
    }
}

// 解密函数,ciphertext 为密文,key 为加密密钥
void decrypt(char ciphertext[], int key) {
    int len = strlen(ciphertext);
    for (int i = 0; i < len; i++) {
        if (ciphertext[i] >= 'a' && ciphertext[i] <= 'z') {
            // 处理小写字母
            ciphertext[i] = (ciphertext[i] - 'a' - key + 26) % 26 + 'a';
        } else if (ciphertext[i] >= 'A' && ciphertext[i] <= 'Z') {
            // 处理大写字母
            ciphertext[i] = (ciphertext[i] - 'A' - key + 26) % 26 + 'A';;
        }
    }
}

int main() {
    char plaintext[100], ciphertext[100];
    int key;
    
    // 读取明文和密钥
    printf("Enter plaintext: ");
    gets(plaintext);
    printf("Enter key: ");
    scanf("%d", &key);
    
    // 加密
    strcpy(ciphertext, plaintext);
    encrypt(ciphertext, key);
    printf("Ciphertext: %s\n", ciphertext);
    
    // 解密
    decrypt(ciphertext, key);
    printf("Decrypted plaintext: %s\n", ciphertext);
    
    return 0;
}

在这个例子中,我们将用户输入的明文和密钥传递给 encrypt 函数,该函数将加密结果存储在了 ciphertext 数组中,我们再将其打印出来。然后,我们调用 decrypt 函数并将 ciphertext 和密钥作为参数传递给它,这个函数将在原地解密密文并将结果存储在 ciphertext 中,最后我们将其打印出来以得到解密后的明文。

需要注意的是,在处理小写和大写字母时要分别加上 'a' 或 'A',并且需要对数字进行模运算以确保使用正常的字母序,使用了 gets 函数读取用户输入,需要小心输入超过字符数组容量时可能导致的缓冲区溢出问题。

相关推荐
PPPPPaPeR.8 小时前
光学算法实战:深度解析镜片厚度对前后表面折射/反射的影响(纯Python实现)
开发语言·python·数码相机·算法
橙露8 小时前
Java并发编程进阶:线程池原理、参数配置与死锁避免实战
java·开发语言
froginwe118 小时前
C 标准库 - `<float.h>`
开发语言
2501_916008899 小时前
深入解析iOS机审4.3原理与混淆实战方法
android·java·开发语言·ios·小程序·uni-app·iphone
小龙报9 小时前
【51单片机】从 0 到 1 玩转 51 蜂鸣器:分清有源无源,轻松驱动它奏响新年旋律
c语言·数据结构·c++·stm32·单片机·嵌入式硬件·51单片机
小武编程9 小时前
基于JL700N可视化SDK的MAC地址应用
c语言·tws耳机·杰理jl700n
Dimpels9 小时前
CANN ops-nn 算子解读:AIGC 批量生成中的 Batch 处理与并行算子
开发语言·aigc·batch
blueSatchel9 小时前
U-Boot载入到DDR过程的代码分析
linux·开发语言·u-boot
无小道9 小时前
QT——QFIie和QFileInfo文件类
开发语言·qt·命令模式
踢足球092910 小时前
寒假打卡:2026-2-7
java·开发语言·javascript