凯撒密码用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 函数读取用户输入,需要小心输入超过字符数组容量时可能导致的缓冲区溢出问题。

相关推荐
兰亭妙微22 分钟前
2026年UX/UI五大趋势:AI、AR与包容性设计将重新定义用户体验
开发语言·ui·1024程序员节·界面设计·设计趋势
懒羊羊不懒@44 分钟前
Java—枚举类
java·开发语言·1024程序员节
m0_748240251 小时前
C++智能指针使用指南(auto_ptr, unique_ptr, shared_ptr, weak_ptr)
java·开发语言·c++
Evand J1 小时前
【MATLAB例程】自适应渐消卡尔曼滤波,背景为二维雷达目标跟踪,基于扩展卡尔曼(EKF)|附完整代码的下载链接
开发语言·matlab·目标跟踪·1024程序员节
百锦再1 小时前
低代码开发的约束性及ABP框架的实践解析
android·开发语言·python·低代码·django·virtualenv·rxjava
csbysj20202 小时前
Scala 字符串
开发语言
自动化小秋葵2 小时前
Python入门经典题目
开发语言·python
Lear3 小时前
C语言与C++在基础语法上的区别
c语言
编程岁月3 小时前
java面试-0305-java线程调度方法?sleep()和wait()区别?
java·开发语言·面试
凌晨一点的秃头猪3 小时前
Python 常见 bug 总结和异常处理
开发语言·python·bug