You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现多密钥Caesar cipher:现有函数仅支持key=123求优化

优化多密钥Caesar密码加密解密函数

问题根源

你的代码仅在密钥为123时生效,是因为你错误地用了索引余数+1(remain + 1)作为偏移量,而非使用密钥字符串中的实际数字。123刚好对应余数0→1、1→2、2→3,才巧合符合预期,换其他密钥就会失效。

优化后的通用代码

以下是支持任意数字密钥的加密解密函数:

function cipher(message, key) {
    // 将密钥字符串转为数字数组
    const keyDigits = key.split('').map(Number);
    let result = '';
    for (let i = 0; i < message.length; i++) {
        // 循环获取对应位置的密钥偏移量
        const shift = keyDigits[i % keyDigits.length];
        // 计算偏移后的字符并拼接结果
        result += String.fromCharCode(message.charCodeAt(i) + shift);
    }
    return result;
}

function deCipher(message, key) {
    const keyDigits = key.split('').map(Number);
    let result = '';
    for (let i = 0; i < message.length; i++) {
        const shift = keyDigits[i % keyDigits.length];
        result += String.fromCharCode(message.charCodeAt(i) - shift);
    }
    return result;
}

// 测试验证
console.log(cipher("hello", "123")); // 输出 'igomq'
console.log(deCipher("igomq", "123")); // 输出 'hello'
console.log(cipher("test", "45")); // 输出 'xiyx'
console.log(deCipher("xiyx", "45")); // 输出 'test'

优化要点

  1. 正确使用密钥数字:将密钥拆分后转为数字数组,循环时根据索引取对应偏移量,而非硬凑余数+1
  2. 简化代码结构:移除冗余中间数组,直接拼接结果字符串,提升性能和可读性
  3. 通用兼容性:支持任意长度的数字密钥(如"45"、"7"、"1234")

可选:仅处理字母的版本(避免非字母乱码)

如果需要只对字母进行偏移,保持非字母字符原样,可使用以下版本:

function cipher(message, key) {
    const keyDigits = key.split('').map(Number);
    let result = '';
    for (let i = 0; i < message.length; i++) {
        const char = message[i];
        const shift = keyDigits[i % keyDigits.length];
        let code = char.charCodeAt(0);
        
        // 处理小写字母
        if (char >= 'a' && char <= 'z') {
            code = ((code - 97 + shift) % 26) + 97;
        } 
        // 处理大写字母
        else if (char >= 'A' && char <= 'Z') {
            code = ((code - 65 + shift) % 26) + 65;
        }
        // 非字母直接保留
        result += String.fromCharCode(code);
    }
    return result;
}

function deCipher(message, key) {
    const keyDigits = key.split('').map(Number);
    let result = '';
    for (let i = 0; i < message.length; i++) {
        const char = message[i];
        const shift = keyDigits[i % keyDigits.length];
        let code = char.charCodeAt(0);
        
        if (char >= 'a' && char <= 'z') {
            code = ((code - 97 - shift + 26) % 26) + 97;
        } else if (char >= 'A' && char <= 'Z') {
            code = ((code - 65 - shift + 26) % 26) + 65;
        }
        result += String.fromCharCode(code);
    }
    return result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:20:32