第八天
Javascript题目
题目 : 写一个加密解密字符串的方法(js)
问题解答
解题思路
- 写一个加密解密字符串的方法, 可以使用动态加密的方法(比如加入随机数和时间戳)来混淆密码, 然后在根据传入的数据进行反解密
时间戳混淆
function encodeStr(str) { let timeC = Date.now().toString().substr(0, 5); // 获取当前的时间戳淆 let a = [',', '[', '-', 'j', '=', 'f', '/', '?', '*', '%'] let newS = '' for (let item of [...str + timeC].reverse()) { //顺序颠倒 newS += a[item] } return newS; } console.log(encodeStr('1321359732')); //数字型字符串//[j-[jf%?j-[/-?% // 解密 function decodeStr(str) { let pwd = str.slice(5) let a = [',', '[', '-', 'j', '=', 'f', '/', '?', '*', '%'] let newS = '' for (let item of [...pwd].reverse()) { // 顺序颠倒 newS += a.indexOf(item) } return newS } console.log(decodeStr('%?-/[-j?%fj[-j[')); //1321359732
使用字符转换加密的方法
//param: method可选参数:encodeStr(加密)与decodeStr(解密)var codeStr = (method, str) => { var hit = method == 'encodeStr' ? '*' : '/'; return [...str].map((item) => { // console.log(item.charCodeAt() + hit + 10); 830/10 或者830*10 return String.fromCharCode(eval(item.charCodeAt() + hit + 10)); }).join('');}console.log(codeStr('decodeStr', '̾ʨ̾ʊː')); //SDSAH //̾ʨ̾ʊː
encodeURIComponent方法
// 0 表示加密 1 表示解密 参数必须为数字型function codeStr(method, str) { if (method === 0) { return btoa(encodeURIComponent(str)) } else if (method === 1) { return decodeURIComponent(atob(str)) } else { return '输入的参数有误' }}console.log(codeStr(0, 'dawd231_Dawd'));
知识扩展
- 获取时间戳的几种方法:
Date.now(); Date.parse()可以自定义获取时间戳的方法, 返回当前时间的时间戳使用这个方法传递参数new Date()即可; +new Date(); new Date().valueOf(); new Date().getTime()时间戳详解 eval()方法返回js语法, 接受字符串 并且可以将接受的字符串转换成js表达式并且立即执行该表达式encodeURLComponent()方法 详解