【C语言】凯赛密码的加密和解密

本文介绍了如何用C语言实现凯撒密码的加密和解密过程,尽管凯撒密码易于理解但安全性较低,现代密码学如AES、RSA更受欢迎。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

凯撒密码是一种简单的替换加密方法,其原理是将明文中的每个字母按照指定的偏移量进行替换,从而得到密文。在下面的C语言代码中,我们实现了凯撒密码的加密和解密过程。这段代码的优点是简单易懂,实现了凯撒密码的基本功能。然而,凯撒密码也有一些明显的缺点和局限性:易被破解、密钥空间有限、无法处理非字母字符、单一性等等。总的来说,凯撒密码作为一种历史悠久但安全性较低的加密算法,在现代密码学中已经不再被广泛使用。现代加密算法如AES、RSA等更加复杂和安全,能够提供更高的数据安全性和保密性 

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

// 凯撒加密函数
void caesar_encrypt(char *plaintext, int key) {
    int i;
    for (i = 0; i < strlen(plaintext); 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';
        }
    }
}

// 凯撒解密函数
void caesar_decrypt(char *ciphertext, int key) {
    int i;
    for (i = 0; i < strlen(ciphertext); 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 the plaintext: ");
    fgets(plaintext, sizeof(plaintext), stdin);
    printf("Enter the key: ");
    scanf("%d", &key);

    // 加密过程
    strcpy(ciphertext, plaintext);
    caesar_encrypt(ciphertext, key);
    printf("Encrypted text: %s\n", ciphertext);

    // 解密过程
    caesar_decrypt(ciphertext, key);
    printf("Decrypted text: %s\n", ciphertext);

    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱因斯坦乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值