• 凯撒密码用c语言实现


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

    1. #include <stdio.h>
    2. #include <string.h>
    3. // 加密函数,plaintext 为明文,key 为加密密钥
    4. void encrypt(char plaintext[], int key) {
    5. int len = strlen(plaintext);
    6. for (int i = 0; i < len; i++) {
    7. if (plaintext[i] >= 'a' && plaintext[i] <= 'z') {
    8. // 处理小写字母
    9. plaintext[i] = (plaintext[i] - 'a' + key) % 26 + 'a';
    10. } else if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') {
    11. // 处理大写字母
    12. plaintext[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
    13. }
    14. }
    15. }
    16. // 解密函数,ciphertext 为密文,key 为加密密钥
    17. void decrypt(char ciphertext[], int key) {
    18. int len = strlen(ciphertext);
    19. for (int i = 0; i < len; i++) {
    20. if (ciphertext[i] >= 'a' && ciphertext[i] <= 'z') {
    21. // 处理小写字母
    22. ciphertext[i] = (ciphertext[i] - 'a' - key + 26) % 26 + 'a';
    23. } else if (ciphertext[i] >= 'A' && ciphertext[i] <= 'Z') {
    24. // 处理大写字母
    25. ciphertext[i] = (ciphertext[i] - 'A' - key + 26) % 26 + 'A';;
    26. }
    27. }
    28. }
    29. int main() {
    30. char plaintext[100], ciphertext[100];
    31. int key;
    32. // 读取明文和密钥
    33. printf("Enter plaintext: ");
    34. gets(plaintext);
    35. printf("Enter key: ");
    36. scanf("%d", &key);
    37. // 加密
    38. strcpy(ciphertext, plaintext);
    39. encrypt(ciphertext, key);
    40. printf("Ciphertext: %s\n", ciphertext);
    41. // 解密
    42. decrypt(ciphertext, key);
    43. printf("Decrypted plaintext: %s\n", ciphertext);
    44. return 0;
    45. }

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

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

  • 相关阅读:
    Java技能树-RE-正则应用-字符串篇
    牛客竞赛每日俩题 - Day6
    使用Ant Design Vue的Table组件,解决点击任意内容详情,点击返回分页器页数默认回到第一页的问题
    何为链表、链表示例以及翻转链表
    老狼数码:电视盒子哪个牌子好?目前最强的电视盒子
    【C++深入浅出】C/C++内存管理(教你如何new到对象)
    Centos7命令行安装Oracle11g
    指针基础 - golang版
    flink入门介绍
    rust重载比较运算符
  • 原文地址:https://blog.csdn.net/2301_78263023/article/details/134450764