【JS加解密】凯撒密码加解密
【代码】
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>凯撒加解密</title> </head> <body onload="main();"> </body> </html> <script type="text/javascript"> <!-- /***************************************************************** * 用chrome浏览器打开执行,ctrl+shift+i看到执行结果。 ******************************************************************/ // 可接受的字符 const SYMBOLS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?,.%'"; // 密钥 const KEY=7; // 代码起始,由body_onload调用 function main(){ console.log("密文="+encrypt("Life is not the amount of breath you take.It's the moments that take you breath away.")); console.log("明文="+decrypt("SpmlApzAuv1A1olAhtv2u1AvmAiylh1oA6v2A1hrlEP1GzA1olAtvtlu1zA1oh1A1hrlA6v2Aiylh1oAh4h6E")); }; // 加密字符串 function encrypt(message){ var msg=message; var key=KEY; const SYM_LENGTH=SYMBOLS.length; var translated=""; for(var i=0;i<msg.length;i++){ var letter=msg.at(i); var idx=SYMBOLS.indexOf(letter); if (idx!=-1 ){ translated+=SYMBOLS.at((idx+key)%SYM_LENGTH); }else{ translated+=letter; } } return translated; } // 解密字符串 function decrypt(message){ var msg=message; var key=KEY; const SYM_LENGTH=SYMBOLS.length; var translated=""; for(var i=0;i<msg.length;i++){ var letter=msg.at(i); var idx=SYMBOLS.indexOf(letter); if (idx!=-1 ){ translated+=SYMBOLS.at((idx-key)%SYM_LENGTH); }else{ translated+=letter; } } return translated; } //--> </script>
【执行结果】
密文=SpmlApzAuv1A1olAhtv2u1AvmAiylh1oA6v2A1hrlEP1GzA1olAtvtlu1zA1oh1A1hrlA6v2Aiylh1oAh4h6E
明文=Life is not the amount of breath you take.It's the moments that take you breath away.
END