在JavaScript中使用Caesar Cipher加密字符串

凯撒密码算法

凯撒密码算法是最简单和最广为人知的加密技术之一。这是一种替换密码,其中明文中的每个字母都由一个字母固定下来,位于字母下方一定位置的位置。

例如

左移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