JS實現客戶端的網頁加密解密技術,可用做選擇性隱蔽展現。固然客戶端的加密安全度是不能與服務器相提並論,確定不能用於密碼這類內容的加密,但對於通常級別的內容用做展現已經夠了。html
JS加密與解密的解決方案有不少,本文則利用String對象的charCodeAt()方法和fromCharCode()方法對字符的ASCII編碼進行獲取和修改。安全
加密,解密代碼:服務器
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 6 <title>網頁加密及解密</title> 7 <meta name="author" content="xiongzaiqiren" /> 8 <meta name="keywords" content="" /> 9 <meta name="description" content="" /> 10 <meta name="generator" content="ClassBao team coding in July 10, 2017" /> 11 12 </head> 13 14 <body> 15 <p><textarea id="text1" name="textfield" cols="50" rows="5">錢莊王員外這我的怎麼樣?</textarea></p> 16 <input type="button" name="Button1" value="加密" onClick="text1.value = MySign.Encrypt(text1.value);"> 17 <input type="button" name="Button2" value="解密" onClick="text1.value = MySign.UnEncrypt(text1.value);"> 18 19 <script language="JavaScript"> 20 var MySign = { 21 //加密/解密次數 22 num: 0, 23 //加密 24 Encrypt: function (Text) { 25 this.num = this.num + 1; 26 output = new String; 27 alterText = new Array(); 28 varCost = new Array(); 29 TextSize = Text.length; 30 for (i = 0; i < TextSize; i++) { 31 idea = Math.round(Math.random() * 111) + 77; 32 alterText[i] = Text.charCodeAt(i) + idea; 33 varCost[i] = idea; 34 } 35 for (i = 0; i < TextSize; i++) { 36 output += String.fromCharCode(alterText[i], varCost[i]); 37 } 38 //text1.value = output; 39 return output; 40 }, 41 42 //解密 43 UnEncrypt: function (Text) { 44 if (this.num > 0) { 45 this.num = this.num - 1; 46 output = new String; 47 alterText1 = new Array(); 48 varCost1 = new Array(); 49 TextSize = Text.length; 50 for (i = 0; i < TextSize; i++) { 51 alterText[i] = Text.charCodeAt(i); 52 varCost[i] = Text.charCodeAt(i + 1); 53 } 54 for (i = 0; i < TextSize; i = i + 2) { 55 output += String.fromCharCode(alterText[i] - varCost[i]); 56 } 57 //text1.value = output; 58 return output; 59 } 60 } 61 }; 62 63 64 //測試代碼 65 var testString = "光頭強,還不去砍樹?"; 66 console.log(testString); 67 68 var sign = MySign.Encrypt(testString); //湊妣o忕ァ[還¬什³呯´硠S桲aチb 69 var sign2 = MySign.UnEncrypt(sign); //光頭強,還不去砍樹? 70 71 console.log(sign); 72 console.log(sign2); 73 74 </script> 75 76 </body> 77 </html>