JAVA中使用MD5加密實(shí)現(xiàn)密碼加密
更新時間:2017年07月06日 14:40:16 作者:Loger丶
本篇文章主要介紹JAVA中使用MD5加密實(shí)現(xiàn)密碼加密,很多地方都要存儲用戶密碼,這里整理了詳細(xì)的代碼,有需要的小伙伴可以參考下
1.新建Md5.java
package com.loger.md5; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; public class Md5 { /**利用MD5進(jìn)行加密*/ public String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{ //確定計算方法 MessageDigest md5=MessageDigest.getInstance("MD5"); BASE64Encoder base64en = new BASE64Encoder(); //加密后的字符串 String newstr=base64en.encode(md5.digest(str.getBytes("utf-8"))); return newstr; } /**判斷用戶密碼是否正確 *newpasswd 用戶輸入的密碼 *oldpasswd 正確密碼*/ public boolean checkpassword(String newpasswd,String oldpasswd) throws NoSuchAlgorithmException, UnsupportedEncodingException{ if(EncoderByMd5(newpasswd).equals(oldpasswd)) return true; else return false; } }
2.新建測試類
package com.loger.md5; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; public class MyTest { public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException { Md5 md5 = new Md5(); String str = "apple"; try { String newString = md5.EncoderByMd5(str); System.out.println(newString); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(md5.EncoderByMd5("apple").equals("HzhwvidPbEmz4xoMZyiVfw==")); } }
運(yùn)行結(jié)果:
說明:
可能會出現(xiàn)找不到 BASE64Encoder 這個類,在eclipse中按住 ctr+shift + T 即可查找到!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
struts1實(shí)現(xiàn)簡單的登錄功能實(shí)例(附源碼)
本篇文章主要介紹了struts1實(shí)現(xiàn)簡單的登錄功能實(shí)例(附源碼),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04Java獲取HttpServletRequest的三種方法詳解
這篇文章主要介紹了Java獲取HttpServletRequest的三種方法詳解,是一個接口,全限定名稱為Jakarta.Serclet.http.HttpServletRequest2023-11-11
HttpServletRequest接口是Servlet規(guī)范的一員,需要的朋友可以參考下JAVA對象和字節(jié)數(shù)組互轉(zhuǎn)操作
這篇文章主要介紹了JAVA對象和字節(jié)數(shù)組互轉(zhuǎn)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08Spring+SpringMVC+Hibernate整合實(shí)例講解
在本篇文章里小編給大家整理的是關(guān)于Spring+SpringMVC+Hibernate整合實(shí)例講解,需要的朋友們可以學(xué)習(xí)下。2020-03-03