java加密MD5實現及密碼驗證


package test;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.junit.Test;

public class Teste {
	@Test
	public void testMd5() {
		System.out.println(encrypt("1234567"));
	}
	
	@Test
	public void testlogin() {
		String password = encrypt("123456adfaf");
		if(encrypt("123456adfaf").equals(password)) {
			System.out.println("密碼正確");
		} else {
			System.out.println("密碼錯誤");
		}
	}
	
	private String encrypt(String password) {
		String passwordMd5 = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] bytes = md5.digest(password.getBytes("utf-8"));
			passwordMd5 = toHex(bytes);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return passwordMd5;
	}
	
	private static String toHex(byte[] bytes) {

	    final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
	    StringBuilder ret = new StringBuilder(bytes.length * 2);
	    for (int i=0; i<bytes.length; i++) {
	        ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
	        ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
	    }
	    return ret.toString();
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM