JavaScript 中的凯撒密码
在本文中,我们将在 JavaScript 源代码中学习和使用 Caesar Cipher。凯撒密码是一种在编程中加密和解密字符串的技术。
凯撒密码
它是加密数据的最简单和最先进的技术之一。在提供的字符串文本中,我们用字母替换和更改每个字母,这是字母表中向下或向上的固定数字。
例如,如果我们定义向上的固定数 3,字符串中的 "A"
将被替换为 "D"
,"B"
将被替换为"E"
,以此类推。
假设我们定义了向上固定数字 3 来移动一个字母;我们的加密将提供一个结果,如下所示。
original string = "hello world"
result string = "khoor zruog"
凯撒密码算法
需要加密的字符串称为文本;首先,我们需要定义 0 到 25 之间的固定数字,因为我们知道字母总数为 26;然后,我们需要遍历一次提供一个字符的文本。
对于每个索引,按照我们已经确定的向下递增或向上递增的规则转换每个字符。最后,我们需要生成结果字符串。
JavaScript 中的凯撒密码
在 JavaScript 中,开发人员大多使用内置或自定义创建的加密技术来保护与服务器交互期间的数据。在 JavaScript Web 应用程序中,我们大部分时间都需要在将数据上传到数据库之前对其进行加密。
我们将在下面创建一个 JavaScript 函数示例,该示例将帮助我们使用凯撒密码技术加密我们的字符串。
例子:
const org = 'hello world';
const createMAp = (alphabets, shift) => {
return alphabets.reduce((charsMap, currentChar, charIndex) => {
const copy = {...charsMap};
let ind = (charIndex + shift) % alphabets.length;
if (ind < 0) {
ind += alphabets.length;
};
copy[currentChar] = alphabets[ind];
return copy;
}, {});
};
const encrypt = (org, shift = 0) => {
const alphabets = 'abcdefghijklmnopqrstuvwxyz'.split('');
const map = createMAp(alphabets, shift);
return org.toLowerCase().split('').map(char => map[char] || char).join('');
};
console.log('original string : ' + org)
console.log('result string :' + encrypt(org, 3))
输出:
"original string : hello world"
"result string :khoor zruog"
在上面的 JavaScript 源代码中,我们创建了 encrypt
函数,其中我们将字符串值和固定数字作为参数传递。我们已经使用 createMap()
函数定义了所有字母并生成了地图对象。
在 createMap()
函数中,我们使用 reduce
方法来生成对象。我们使用了 toLowerCase()
和 split()
方法来避免和生成新字符串,避免具有固定数字 3 的特殊字符。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。