使用 JavaScript 中的凱撒密碼加密字串


凱撒密碼演算法

凱撒密碼演算法是最簡單、最著名的加密技術之一。它是一種替換密碼,其中密文中每個字母都由字母表中位置向後或者向前的若干固定數量位置的字母替換。

比如

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

更新日期:2020-12-11

584 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.