【C语言】单表交换密码的加密解密

单表交换密码是一种简单但不够安全的加密方法,它适用于对简单文本进行加密,但不适用于对于保密性要求较高的数据。使用时需要注意,密钥(即密钥表)应为字母表的一个排列,它将明文中的每个字母映射到一个不同的字母上。用户输入密钥时,应保证其长度为26,并且包含字母表的每个字母,且每个字母仅出现一次。在实际应用中,应使用更为复杂和安全的加密算法来保护数据的安全

解题 思路:

先接收用户输入的明文和密钥表,创建一个加密函数monoalphabetic_encrypt,该函数有两个参数:plainText是待解密的密文字符串,key是密钥表。加密思路为:用户输入明文和加密密钥,密钥是一个字母表的排列-->根据密钥,将明文中的每个字母替换为密钥表中对应位置的字母-->加密完成后,输出密文。

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

// 单表交换加密函数
void monoalphabetic_encrypt(char *plaintext, char *key) {
    int i;
    for (i = 0; i < strlen(plaintext); i++) {
        // 加密大写字母
        if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') {
            plaintext[i] = key[plaintext[i] - 'A'];
        }
        // 加密小写字母
        else if (plaintext[i] >= 'a' && plaintext[i] <= 'z') {
            plaintext[i] = tolower(key[plaintext[i] - 'a']);
        }
    }
}

// 单表交换解密函数
void monoalphabetic_decrypt(char *ciphertext, char *key) {
    int i;
    for (i = 0; i < strlen(ciphertext); i++) {
        // 解密大写字母
        if (ciphertext[i] >= 'A' && ciphertext[i] <= 'Z') {
            int j;
            for (j = 0; j < 26; j++) {
                if (key[j] == ciphertext[i]) {
                    ciphertext[i] = 'A' + j;
                    break;
                }
            }
        }
        // 解密小写字母
        else if (ciphertext[i] >= 'a' && ciphertext[i] <= 'z') {
            int j;
            for (j = 0; j < 26; j++) {
                if (tolower(key[j]) == ciphertext[i]) {
                    ciphertext[i] = 'a' + j;
                    break;
                }
            }
        }
    }
}

int main() {
    char plaintext[100], ciphertext[100], key[26];
    int i;

    printf("Enter the plaintext: ");
    fgets(plaintext, sizeof(plaintext), stdin);

    printf("Enter the key (a permutation of the alphabet): ");
    fgets(key, sizeof(key), stdin);

    // 去除密钥中的换行符
    key[strcspn(key, "\n")] = '\0';

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

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

    return 0;
}
相关推荐
Evand J3 分钟前
【MATLAB例程】AOA与TDOA混合定位例程,适用于三维环境、4个锚点的情况,附下载链接
开发语言·matlab
机器视觉知识推荐、就业指导3 分钟前
Qt 与Halcon联合开发八: 结合Qt与Halcon实现海康相机采图显示(附源码)
开发语言·数码相机·qt
Heartoxx31 分钟前
c语言-指针与一维数组
c语言·开发语言·算法
hqxstudying33 分钟前
Java创建型模式---原型模式
java·开发语言·设计模式·代码规范
charlie1145141911 小时前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
神仙别闹1 小时前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
chao_7892 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
秋说2 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
森焱森3 小时前
APM与ChibiOS系统
c语言·单片机·算法·架构·无人机
尘世闲鱼4 小时前
解数独(C++版本)
开发语言·c++·算法·解数独