您的位置:首頁技術文章
文章詳情頁

SpringBoot實現Mysql使用MD5進行密碼加密的示例

瀏覽:80日期:2023-03-15 18:30:22

項目開發中為了保護用戶隱私安全,一般都會用MD5進行密碼加密

以下就簡單舉例SpringBoot 實現Mysql使用MD5進行密碼加密做一個簡單的例子

看下數據庫,這邊簡單做了用戶表進行測試

SpringBoot實現Mysql使用MD5進行密碼加密的示例

pom.xml添加依賴引用

<!--MD5加密 對注冊的密碼進行加密操作--><dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId></dependency><dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version></dependency>

創建unit包創建md5加密類,進行密碼加密

package com.wyh.unit;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/** * @date 2021/4/20 23:34 */public class Md5Utils { /* * md5算法進行密碼加密 * */ public static String code(String str){try{ //1.獲取MessageDigest對象 生成一個MD5加密計算摘要 MessageDigest md = MessageDigest.getInstance('MD5') ; /* str.getBytes() * 使用平臺的默認字符集將此 String 編碼為 byte 序列,并將結果存儲到一個新的 byte 數組中. 此方法多用在字節流中,用與將字符串轉換為字節。 * */ // 計算md5函數 使用指定的字節數組更新摘要md md.update(str.getBytes()); /* * digest()最后確定返回md5 hash值,返回值為8的字符串。 * 因為md5 hash值是16位的hex值,實際上就是8位的 * */ byte[] byteDigest = md.digest() ; int i ; StringBuffer buf = new StringBuffer('') ; //遍歷byteDigest //加密邏輯,可以debug自行了解一下加密邏輯 for(int offset = 0 ; offset<byteDigest.length ; offset++){i = byteDigest[offset] ;if(i < 0) i += 256 ;if(i < 16) buf.append('0') ;// BigInteger函數則將8位的字符串轉換成16位hex值,用字符串來表示;得到字符串形式的hash值buf.append(Integer.toHexString(i)) ; } return buf.toString() ;}catch (NoSuchAlgorithmException e){ e.printStackTrace(); return null ;} }}

添加頁面

<%-- Date: 2021/4/21 Time: 0:04--%><%@ page contentType='text/html;charset=UTF-8' language='java' %><html><head> <title>添加用戶</title></head><body> <form action='/addUser' method='post'>用戶名<input type='text' name='username'/><br>賬號<input type='text' name='account'/><br>密碼<input type='password' name='password'/><br><input type='submit' value='提交'> </form></body></html>

Controller添加方法

@RequestMapping('/addUser') public String addUser(User user){//MD5方法對密碼進行加密處理String password= Md5Utils.code(user.getPassword()) ;user.setPassword(password);int i = userService.addUser(user);if(i>0){ return 'redirect:/showAllUser';} return ''; }

進行添加測試,這邊我輸入的密碼是123456

SpringBoot實現Mysql使用MD5進行密碼加密的示例

查看數據庫

SpringBoot實現Mysql使用MD5進行密碼加密的示例

進行解密可以去:https://www.cmd5.com/復制數據庫的加密密碼即可

SpringBoot實現Mysql使用MD5進行密碼加密的示例

到此這篇關于SpringBoot實現Mysql使用MD5進行密碼加密的示例的文章就介紹到這了,更多相關SpringBoot MD5密碼加密內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
国产综合久久一区二区三区