You need to enable JavaScript to run this app. C语言Vigenere加密代码调整:实现扩展密钥对齐原字符串空格
优惠活动
大模型
产品
解决方案
定价
更多

C语言Vigenere加密代码调整:实现扩展密钥对齐原字符串空格

维吉尼亚密码空格对齐逻辑修复

现有代码核心问题

  • 遍历明文生成密钥时,没有对空格位置做特殊判断,所有位置都推进密钥循环游标,导致密钥序列连续拼接,和明文的空格结构完全错位
  • 加密计算阶段没有跳过空格,会把空格字符也按字母规则做模26运算,破坏明文原本的格式
  • 原大写转换逻辑没有过滤占位符,所有字符(包括空格)都纳入遍历计数,逻辑冗余
  • 原capital函数定义为void无返回值类型,却编写了return str[j]的返回语句,存在编译警告风险
  • 使用gets函数读取输入,无长度限制,存在数组越界的安全隐患

修复后的实现逻辑

  • 逐位遍历明文生成扩展密钥:遇到明文空格时,对应密钥位置直接写入空格,且不推进密钥的循环游标;遇到字母时,从当前游标位置取密钥字符,再将游标后移到下一位,循环到密钥末尾时自动回到起点
  • 加密计算同步逐位处理:遇到空格直接输出空格,不执行字母的加模运算;遇到字母时按维吉尼亚规则计算密文
  • 替换不安全的输入函数,改用带长度限制的fgets读取输入,消除越界风险

修复后完整可运行代码

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

void str_toupper_keep_space(char str[100]){
    // 保留空格格式,仅将字母转换为大写
    for(int i = 0; str[i] != '\0'; i++){
        if(isalpha(str[i])){
            str[i] = toupper(str[i]);
        }
    }
}

int main()
{
    int numstr[100], numkey[100], numcipher[100];
    char str[100], key[100], newKey[100];
    printf("Enter a string : ");
    fgets(str, sizeof(str), stdin);
    // 移除fgets读取到的末尾换行符
    str[strcspn(str, "\n")] = '\0';

    str_toupper_keep_space(str);
    printf("Entered string is : %s \n", str);

    printf("Enter a key : ");
    fgets(key, sizeof(key), stdin);
    key[strcspn(key, "\n")] = '\0';
    str_toupper_keep_space(key);

    int plain_len = strlen(str);
    int key_len = strlen(key);
    int key_cursor = 0; // 密钥游标,遇到明文空格时不推进

    for(int i = 0; i < plain_len; i++){
        if(str[i] == ' '){
            // 空格位置直接占位,不参与加密,不移动密钥游标
            newKey[i] = ' ';
            numcipher[i] = ' ';
        } else {
            // 普通字母位置生成对应密钥、执行加密
            newKey[i] = key[key_cursor];
            numstr[i] = str[i] - 'A';
            numkey[i] = key[key_cursor] - 'A';
            numcipher[i] = numstr[i] + numkey[i];
            // 模26处理保证密文在A-Z范围内
            if(numcipher[i] > 25){
                numcipher[i] -= 26;
            }
            // 推进密钥游标,到密钥末尾时循环回起点
            key_cursor++;
            if(key_cursor == key_len){
                key_cursor = 0;
            }
        }
    }
    newKey[plain_len] = '\0'; // 补充字符串结束符

    // 输出结果
    printf("New Key : %s \n", newKey); 
    printf("Vigenere Cipher text is : ");   
    for(int i = 0; i < plain_len; i++)
    {
        if(numcipher[i] == ' '){
            printf(" ");
        } else {
            printf("%c", numcipher[i] + 'A'); 
        }
    }
    printf("\n");
}

测试验证效果

使用场景给定的测试值输入:

  • 明文:adiva fiqri
  • 密钥:div

程序输出结果:

New Key : divdi vdivd
Vigenere Cipher text is : DSEDM AYKZL

完全匹配预期的密钥结构对齐要求。

内容的提问来源于stack exchange,提问作者Adiva Fiqri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.13 07:06:04