简单的JavaScript字符串加密解密
简单的JavaScript字符串加密解密
1 <div> 2 <input type="text" id="input" autofocus="autofocus"> 3 <button type="button" onclick="submit()">click</button> 4 </div>
1 <script> 2 // 加密 3 function encryption(str) { 4 5 let newstr = []; 6 let number = Math.random()*200; // 0 ~ 接近200 7 number = Math.trunc(number) // 0 ~ 199 8 9 for (let i = 0; i < str.length; i++) { 10 11 newstr.push(str.charCodeAt(i) + number); 12 13 } 14 newstr.push(number) 15 return escape(newstr.toString()); 16 } 17 18 // 解密 19 function decrypt(str) { 20 21 str = unescape(str); 22 23 // 把字符串以逗号切割为数组 24 let arr = str.split(','); 25 let number = arr.pop(); 26 27 let newarr = []; 28 arr.forEach(function (item) { 29 let temp = String.fromCharCode(item - number); 30 newarr.push(temp) 31 }); 32 33 return newarr.join(''); 34 } 35 36 37 function submit() { 38 var input = document.getElementById('input'); 39 var value = input.value; 40 41 console.log("加密前: ", input.value); 42 43 let a = encryption(value); 44 console.log("加密后: ", a ); 45 console.log("解密前: "+ a); 46 47 console.log("解密后: ", decrypt(a )); 48 49 } 50 51 </script>