使用 JavaScript 中的凯撒密码加密字符串

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/21 21:00:17

凯撒密码算法

凯撒密码算法是最简单、最广为人知的加密技术之一。它是一种替换密码,其中明文中的每个字母都被字母表中某个固定位置的字母替换。

例如

左移 3 位,D 将被 A 替换,E 将成为 B,依此类推。我们需要编写一个 JavaScript 函数,将要加密的字符串作为第一个参数,将移位量作为第二个参数。

移位量可以是正整数或负整数(正移位表示向右移位,负移位表示向左移位)。

示例

以下是代码 −

const str = 'thisIsAString';
const getMap = (legend, shift) => {
   return legend.reduce((charsMap, currentChar, charIndex) => {
      const copy = { ...charsMap };
      let ind = (charIndex + shift) % legend.length;
      if (ind < 0) {
         ind += legend.length;
      };
      copy[currentChar] = legend[ind];
      return copy;
   }, {});
};
const encrypt = (str, shift = 0) => {
   const legend = 'abcdefghijklmnopqrstuvwxyz'.split('');
   const map = getMap(legend, shift);
   return str
   .toLowerCase()
   .split('')
   .map(char => map[char] || char)
   .join('');
};
console.log(encrypt(str, 6));

输出

以下是控制台上的输出 −

znoyoygyzxotm

相关文章


有用资源