在网页登录时,我们会经常用到password输入框,使用post提交到后台验证。
密码明码提交很容易被人截获或记录。
我们可以通过JS将密码简单加密,在后台再解密,防止传输过程中监听或泄漏。
网页端代码:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="renderer" content="webkit"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>密码加密传输</title> <link href="https://lib.baomitu.com/normalize/latest/normalize.min.css" rel="stylesheet"> <script src="https://lib.baomitu.com/jquery/3.4.1/jquery.min.js"></script> <style> body { padding: 0 10px; } </style> </head> <body> <h1>密码加密传输测试</h1> <form id="frm1" action="login.php" method="POST" style="line-height: 2;"> <input id="pwd" type="hidden" name="pwd" /> 账户:<input type="text" name="account" autofocus required /><br> 密码:<input id="txtPwd" type="password" required /><br>    <input type="submit" value="登录" /> </form> <script> function base64_encode(str) { str = window.btoa(str); let str1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; let str2 = 'L73hz/sHgnKmQCD8YFfGj1toaR0S4JcTpi6rv5yw+BVbWPeNu2IlUOxEdqkM9XZA-'; let str3 = ''; for (let i = 0; i < str.length; i++) { let k = str1.indexOf(str[i]); str3 += str2[k]; } return str3; } $(function () { $('#frm1').submit(function () { $('#pwd').val(base64_encode($('#txtPwd').val())); }); }); </script> </body> </html>
后台PHP处理代码:
<?php $account = $_POST['account']; $password = $_POST['pwd']; // 解析密码 str_shuffle 打乱字符串 $str1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; $str2 = 'L73hz/sHgnKmQCD8YFfGj1toaR0S4JcTpi6rv5yw+BVbWPeNu2IlUOxEdqkM9XZA-'; $str3 = ''; for ($i=0; $i<strlen($password); $i++) { $str3 .= $str1[strpos($str2, $password[$i])]; } $password = base64_decode($str3); if ($account == 'admin' && $password == 'admin01') { echo '登录成功'; } else { echo '登录失败'; }