Comments (22)
// 利用 base64, 浏览器环境自带 btoa / atob 方法
// Node.js 需要引入相关库
const str = "abcdefg";
console.log(btoa(str));
console.log(atob(btoa(str)));
// 凯撒密码
const encodeCaesar = ({str = "", padding = 3}) =>
!str
? str
: str
.split("")
.map((s) => String.fromCharCode(s.charCodeAt() + padding))
.join("");
const decodeCaesar = ({str = "", padding = 3}) =>
!str
? str
: str
.split("")
.map((s) => String.fromCharCode(s.charCodeAt() - padding))
.join("");
console.log(encodeCaesar({str: "hello world"}));
console.log(decodeCaesar({str: "khoor#zruog"}));
from fe-interview.
仅支持浏览器端:
function encode (str) {
return btoa(encodeURIComponent(str));
}
function decode (str) {
return decodeURIComponent(atob(str));
}
源自阮一峰《JavaScript 标准教程》
from fe-interview.
js生成动态密文
前端生成的密文虽然谈不上安全,但是可以用于混淆文本,防止一些参数被猜到.
特点:
每次生成的密文都不一样,解密后的文本一样
原理:
加密:
将字符串中的字符拆分成数组并将其转为字符的八进制Unicode码->反序->分割字符串->在字符串中随机加入小写字母,将分割符替换为随机大写字母
这样最终生成了 由数字/小写字母/大写字母的 动态密文
解密:
去掉小写字母->将大写字母替换为一个分割符并用分割符 拆分字符串为数组->反序->将八进制Unicode码转字符串->将数组合并成字符串
使用场景:
隐藏一些不想让用户直接看见的参数, 比如 url中的 id 等参数,cookies中的信息等
生活使用:
也可将自己常用的密码加密后保存在电脑上,避免密码被直接暴露.
//加密
function encodeStr(str) {
if (!str) return;
var random = function (lower, upper) {
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
};
var arr = str.toString().split("").map(function (item) {
return item.charCodeAt(0).toString(8)
});
arr.reverse();//反序数组
arr = arr.join("").split("");//暂时使用 _ 分割字符串;
var num = 0;
while (num < str.length) {
var r = String.fromCharCode(random(97, 122));//生成用于混淆的 的 小写字母
arr.splice(random(0, arr.length), 0, r);
num++;
}
return arr.join("").replace(//ig, function (str) {
return String.fromCharCode(random(65, 90));
});//将分割符 _ 替换为随机的 大写字母
}
//解密
function decodeStr(str) {
if (!str) return;
var temp = [];
str.split("").forEach(function (item) {
var code = item.charCodeAt(0);
if (code <= 90 && code >= 65) {
item = "";//将作为分割用的 随机大写字母 统一为 _ 以便切割
temp.push(item);
}else if (code <= 57 && code >= 48) {
temp.push(item);//提取 数字
}
});
temp = temp.join("").split("");
temp.reverse();
var res = temp.map(function (item) {
return String.fromCharCode(parseInt(item, 8));
});
return res.join("");
}
https://www.crazyming.com/note/1704/
from fe-interview.
function strEncrypt(str) {
return str.split('').map(s => {
return String.fromCharCode(s.charCodeAt() + 1)
}).join('')
}
console.log(strEncrypt('hello world')) // ifmmp!xpsme
from fe-interview.
//param: method可选参数:encodeStr(加密)与decodeStr(解密)
var codeStr=(method,str)=>{
var hit = method=='encodeStr'?'*':'/';
return [...str].map((item)=>{
return String.fromCharCode(eval(item.charCodeAt()+hit+10));
}).join('');
}
console.log(codeStr('encodeStr','SDSAH'));
from fe-interview.
function encodeStr(str, key) {
return str
.split("")
.map(item => {
return item.charCodeAt() * key;
})
.join("#");
}
function decodeStr(str, key) {
return str
.split("#")
.map(item => {
return String.fromCharCode(+item / key);
})
.join("");
}
console.log(decodeStr(encodeStr("hello world", 665), 665));
from fe-interview.
字符转换
// 字符转换加密/解密
function strEnDecrypt(str, method) {
// 加解密对应不同运算符(默认解密)
let operator = method === "encrypt" ? "*" : "/";
return [...str]
.map((char) => {
return String.fromCharCode(eval(char.charCodeAt() + operator + 10));
})
.join("");
}
console.log(strEnDecrypt("absgdi", "encrypt"));
console.log(strEnDecrypt("ϊϔѾІϨК", "decrypt"));
encodeURIComponent 方法
// encodeURIComponent方法
function strEnDecrypt1(str, method) {
// 0加密 1解密
if (method === 0) {
return btoa(encodeURIComponent(str));
} else if (method === 1) {
return decodeURIComponent(atob(str));
} else {
return "输入参数不正确";
}
}
console.log(strEnDecrypt1("absgdi", 0));
console.log(strEnDecrypt1("YWJzZ2Rp", 1));
时间戳混淆(数字型字符串)
function strEncrypt(str) {
let timeCon = Date.now().toString().substr(0, 5); // 时间戳转字符串取前五位
let order = [",", "[", "-", "j", "=", "f", "/", "?", "*", "%"];
let newStr = "";
for (let char of [...(str + timeCon)].reverse()) {
newStr += order[char];
}
return newStr;
}
function strDecrypt(str) {
let pwd = str.slice(5);
let order = [",", "[", "-", "j", "=", "f", "/", "?", "*", "%"];
let newStr = "";
for (let char of [...pwd].reverse()) {
newStr += order.indexOf(char);
}
return newStr;
}
console.log(strEncrypt("2323232"));
console.log(strDecrypt("-fj/[-j-j-j-"));
XOR加密
// XOR加密
// 生成一个随机的 key
// 生成一个随机整数
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// 生成一个随机的十六进制数
function getHex() {
let n = 0;
for (let i = 4; i > 0; i--) {
n = getRandomInt(0, 1) << (i - 1 + n);
}
return n.toString(16);
}
// 生成一个32位的十六进制值,用作一次性key
function getOTP() {
const arr = [];
for (let i = 0; i < 32; i++) {
arr.push(getHex());
}
return arr.join("");
}
// XOR运算
function getXOR(message, key) {
const arr = [];
for (let i = 0; i < 32; i++) {
const m = parseInt(message.substr(i, 1), 16);
const k = parseInt(key.substr(i, 1), 16);
arr.push((m ^ k).toString(16));
}
return arr.join("");
}
function xorEncrypt(password) {
const message = md5(password);
const key = getOTP();
return getXOR(password, key);
}
console.log(xorEncrypt("1232aewes"));
from fe-interview.
escape("我是被简单的加密了") // "%u6211%u662F%u88AB%u7B80%u5355%u7684%u52A0%u5BC6%u4E86"
from fe-interview.
题目应该加密和解密同时实现吧
from fe-interview.
@kokokele 你可以同时实现出来
from fe-interview.
//第8天 写一个加密字符串的方法
function strEncrypt(str) {
var sault = 3;
return str
.split("")
.map(c => {
return String.fromCharCode(c.charCodeAt(0) + sault);
})
.join("");
}
function strDecrypt(str) {
var sault = 3;
return str
.split("")
.map(c => {
return String.fromCharCode(c.charCodeAt(0) - sault);
})
.join("");
}
var str = "hello, world";
console.log(strEncrypt(str));
console.log(strDecrypt(strEncrypt(str)));
from fe-interview.
var str="abcdqwa";
var newStr="";
function encrypt(str){
for(var i=0;i<str.length;i++){
newStr+=String.fromCharCode(str[i].charCodeAt()+10);
};
return newStr;
};
function decrypt(newStr){
var char="";
for(var i=0;i<newStr.length;i++){
char+=String.fromCharCode(newStr[i].charCodeAt()-10);
};
return char;
}
from fe-interview.
function fn(str) {
return str.replace(/\w/g, (s) => {
var code = s.charCodeAt();
if (code <= 77) {
return String.fromCharCode(code + 13);
} else {
return String.fromCharCode(code - 13);
}
})
}
console.log(fn("my family"));//`l YT`\_l
from fe-interview.
function fn(str) { return str.replace(/\w/g, (s) => { var code = s.charCodeAt(); if (code <= 77) { return String.fromCharCode(code + 13); } else { return String.fromCharCode(code - 13); } }) } console.log(fn("my family"));//`l YT`\_l
这么搞你怎么解密
from fe-interview.
btoa与atob
只能加密ascii,不能加密汉字。
encodeURIComponent
只能将中文加密,不可以加密ascii
加密时 可以先将中文加密,然后再用btoa加密
解密时可以先将ascii解密,然后再将非ascii解密
var str = 'i love**';
// 加密
var jiaMi = encodeURIComponent(str);
var jiaM = btoa(jiaMi);
//解密,先用atob解密ascii码,然后再用decodeURIComponent
var jieMi = atob(jiaM);
var jieM = decodeURIComponent(jieMi);
from fe-interview.
贴一个每次生成不同的密文同时支持解密的方法。
思路
- 获取原字符串中每个字符的unicode码
- 每一位之前插入随机数
- 合成新的字符串
- 解码的时候排除掉随机数
function extend(num, len) {
let res = `${num}`;
while (res.length < len) {
res = "0" + res;
}
return res;
}
function random() {
return Math.floor(Math.random() * 10);
}
function encrypt2(str) {
return Array.from(str)
.map((ele) => {
// 生成随机数,扩展原字符的编码从8至16
const code = ele.charCodeAt();
const extendedCode = extend(code, 8);
const r1 = extendedCode.split("").map((ele) => {
return random() + ele
}).join('')
return r1;
})
.map((ele) => {
// 分成四组,每组四个数字
const arr = [];
for (let i = 0; i < ele.length; i = i + 4) {
const s1 = ele.substr(i, 4);
arr.push(s1);
}
return arr;
})
.map((ele) => {
// 合成最终的字符串
return ele
.map((i) => {
return String.fromCharCode(Number(i) + 33); // 这里33是因为ascii码中0~31是不可显字符,32是空格
})
.join("");
})
.join("");
}
function decrypt2(str) {
const arr = [];
for (let i = 0; i < str.length; i = i + 4) {
arr.push(str.substr(i, 4));
}
return arr.map((ele) => {
return ele.split("").map((i) => {
return extend(i.charCodeAt() - 33, 4);
}).join('');
}).map((ele) => {
const targets = []
for (let i = 1; i < ele.length; i = i+2) {
targets.push(ele[i])
}
return String.fromCharCode(Number(targets.join('')))
});
}
var encrypted = encrypt2("hello你好");
console.log(encrypted);
console.log(decrypt2(encrypted));
ή⎣Ꮢ௧ࡁᏜѤ⍝ѣᯑgល,⎗࿕{вࡖᏻ⎒ᏹࠥ
[ 'h', 'e', 'l', 'l', 'o', '你', '好' ]
ѣࡁ⎉ៃ࠭ᐄఋ࠷J់ᯓဇ២Яရᾱࠤ⏠⍉ЩᾪᑱAᢼ⎬
[ 'h', 'e', 'l', 'l', 'o', '你', '好' ]
gࡋѐួࡋ௭߲њ⍻ᾝ᮳ᐃх࿖ࠫΆఋធ⍩ឨउ᭹⍋①တ
[ 'h', 'e', 'l', 'l', 'o', '你', '好' ]
from fe-interview.
// 写一个加密字符串的方法 加密方法:每个字符等于字符的Unicode码+2
let myString = '[email protected]';
//加密
function encryptionString(str) {
let newStr = new String;
// str = str.reverse();
for(let i = 0; i < str.length; i++) {
newStr += String.fromCharCode((str.charCodeAt(i) + 2));
}
console.log(newStr);
return newStr;
}
//解密
function decodeString(str) {
let oldStr = new String;
for(let i = 0; i < str.length; i++) {
oldStr += String.fromCharCode((str.charCodeAt(i) - 2));
}
console.log(oldStr);
return oldStr;
}
let newStr = encryptionString(myString);
decodeString(newStr);
from fe-interview.
const str = "hello world";
function enCode(str) {
let key = String.fromCharCode(str.charCodeAt(0) + str.length);
for (let i = 1; i < str.length; i++) {
key += String.fromCharCode(str.charCodeAt(i) + str.charCodeAt(i - 1));
}
return escape(key);
}
function deCode(code) {
code = unescape(code);
let key = String.fromCharCode(code.charCodeAt(0) - code.length);
for (let i = 1; i < code.length; i++) {
key += String.fromCharCode(code.charCodeAt(i) - key.charCodeAt(i - 1));
}
return key;
}
let code = enCode(str);
console.log(deCode(code));
from fe-interview.
let code = escape("hello_world");
let decode = unescape(code);
console.log(decode);
from fe-interview.
function encode (str) {
return btoa(encodeURIComponent(str));
}
function decode (str) {
return decodeURIComponent(atob(str));
}
console.log(encode(str))
console.log(decode(encode(str)))
from fe-interview.
// 写一个加密字符串的方法
// 第一种 利用window自带的btoa
let str4 = 'hello xq 我'
encodeURIComponent
function encodeStr(str, gap = 6) {
// btoa 不能识别中文
// return btoa(encodeURIComponent(str))
// 第二种 利用 Unicode编码来加密
return str.split('').map(s => {
return String.fromCharCode(s.charCodeAt() + gap)
}).join('')
}
function decodeStr(str, gap = 6) {
// return decodeURIComponent(atob(str))
return str.split('').map(s => {
return String.fromCharCode(s.charCodeAt() - gap)
}).join('')
}
console.log(decodeStr(encodeStr(str4)))
from fe-interview.
function encryptString(str) {
let encryptedStr = ""; // 存放加密后的结果
for (let i = 0; i < str.length; i++) {
const charCode = str[i].charCodeAt(); // 获取每个字符的ASCII值
if (/^[a-zA-Z]$/.test(str[i])) { // 判断当前字符是否为英文字母
const shiftedCharCode = (charCode + 13) % 26; // 将字符向右移动13位(模运算)
encryptedStr += String.fromCharCode(shiftedCharCode); // 转换成对应的字符并添加到加密结果中
} else {
encryptedStr += str[i]; // 非英文字母直接保持不变
}
}
return encryptedStr;
}
// 测试加密函数
const originalStr = "Hello World!";
console.log("原始字符串:", originalStr);
const encryptedStr = encryptString(originalStr);
console.log("加密后的字符串:", encryptedStr);
from fe-interview.
Related Issues (20)
- [angular] 第1824天 请说说在Angular中的Change Detection是什么?如何优化应用程序的性能?
- [angular] 第1825天 请说说在Angular中的NgModule是如何工作的?它有哪些功能?
- [angular] 第1826天 请说说在Angular中的动态组件是什么?
- [angular] 第1827天 在Angular中怎样创建一个动态组件?
- [angular] 第1828天 在Angular中怎样创建一个服务工厂?
- [angular] 第1829天 请说说在Angular中的RxJS是什么?
- [angular] 第1830天 请说说在Angular中的单元测试是什么?
- [angular] 第1831天 在Angular中怎样写一个单元测试?
- [angular] 第1832天 请说说在Angular中的服务工厂是什么?
- [angular] 第1833天 在Angular中怎样使用RxJS?
- [angular] 第1834天 在Angular中有哪些常用的装饰器?
- [angular] 第1835天 请说说在Angular中组件初始化时,生命周期钩子的调用顺序
- [angular] 第1836天 在Angular中父子之间是如何通信的?
- [angular] 第1837天 AngularJS和Angular有什么区别?
- [angular] 第1838天 在Angular中的onpush策略下什么时候会解变更检测?
- [angular] 第1839天 在Angular中的数据绑定是采用什么机制?
- [js] 第1840天 请说说你对Promise.allSettled()的了解 HOT 1
- [angular] 第1841天 请说说什么是Angular CLI构建器?
- [angular] 第1842天 你有看过Angular的源码吗?
- [angular] 第1843天 请说说使用Angular有哪些优势?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fe-interview.