摘要算法
摘要算法也稱為哈希算法、散列列算法,可以將任意長度的數據轉換成一個定長的、不可逆的數字。只要原
文本不不同,計算的結果必然不同(幾乎不用考慮重復的情況)。摘要算法⽤用於對比信息源是否一致,因為
只要數據源發生變化,得到的摘要信息必然不同,通常用於簽名校驗。
消息摘要算法的特點:
- 無論輸入的消息有多長,計算出來的消息摘要的長度總是固定的。
- 消息摘要不是真正的隨機,因為用相同的算法對相同的消息求兩次摘要,其結果必然相同
- 消息摘要函數是無陷⻔門的單向函數,即只能進行正向的信息摘要,而無法從摘要中恢復出任何的消息,甚⾄至根本就找不到任何與原信息相關的信息
常見的摘要算法有:MD5、SHA-1、MAC、CRC等;
sha1與md5的區別:https://www.cnblogs.com/scu-cjx/p/6878853.html
下載前端加密需要用到的js,http://pajhome.org.uk/crypt/md5/
測試
使用md5.js
<script type="text/javascript" src="js/md5-min.js"></script> <script type="text/javascript"> var hex = hex_md5("admin"); console.log(hex); </script>
使用md5前台加密加鹽+后台加密加鹽注冊:
1、前端頁面
$("#registerbtn").click(function () { var username = $("#username").val(); //使用md5加密加鹽 var salt = "hhj" var password = hex_md5($("#rpassword2").val()+salt); //加密方法 $.post("/user/registered", { "username":username, "password":password } , function (rs) { console.log(rs); }, "json"); });
2、后台工具類
public class EncryptUtils { //自定義鹽值 public static final String SALT = "itheima"; //MD5加密 public static String md5s(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return str; } }
sha1 工具類:

public static String SHA1(String decript) { try { MessageDigest digest = MessageDigest .getInstance("SHA-1"); digest.update(decript.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字節數組轉換為 十六進制 數 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
3、后台service方法的編寫
@Override public boolean register(T_user user) throws Exception { //使用md5進行二次加密加鹽 user.setPassword(EncryptUtils.md5s(user.getPassword() + EncryptUtils.SALT)); return userMapper.insert(user) > 0 ? true : false; }
數據庫中密碼字段顯示密文:
登錄用戶(輸入密碼再次加密判斷是否與數據庫中的一致)
1、前端頁面(注意加密方法、鹽值必須一致)
$("#loginbtn").click(function(){ //使用md5加密加鹽 var salt="hhj"; var rpassword=hex_md5($("#rpassword").val()+salt); 。。。
2、后台驗證
@Override public T_user login(T_user user) throws Exception { //使用md5進行二次加密加鹽 user.setPassword(EncryptUtils.md5s(user.getPassword() + EncryptUtils.SALT)); QueryWrapper<T_user> query = new QueryWrapper<>(); query.eq("password", password); return userMapper.selectOne(query); }