可以使用简单的加密和解密算法,例如凯撒密码、替换密码等。
以下是一种将字符串按一定规则替换后进行加密和解密的示例:
// 加密函数
function encrypt(str) {
// 将字符串转换为所有小写字母
str = str.toLowerCase();
let result = "";
// 循环遍历字符串,对于每个字符进行替换
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
// 如果字符是小写字母,将其替换为另外一个小写字母
if (charCode >= 97 && charCode <= 122) {
result += String.fromCharCode(97 + (charCode - 97 + 3) % 26);
} else {
result += String.fromCharCode(charCode);
}
}
return result;
}
// 解密函数
function decrypt(str) {
let result = "";
// 循环遍历字符串,对于每个字符进行替换
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
// 如果字符是小写字母,将其替换为另外一个小写字母
if (charCode >= 97 && charCode <= 122) {
result += String.fromCharCode(97 + (charCode - 97 + 23) % 26);
} else {
result += String.fromCharCode(charCode);
}
}
return result;
}
// 使用示例
let encrypted = encrypt("Hello, world!");
console.log("Encrypted: ", encrypted); // 输出:khoor, zruog!
let decrypted = decrypt(encrypted);
console.log("Decrypted: ", decrypted); // 输出:hello, world!