使用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP