在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
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西