1. 程式人生 > >(五)密碼加密

(五)密碼加密

cep pla runtime ati etc 激活碼 msg [] javax

package com.louis.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
    /**
     * 使用md5加密
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try
{ //普通的字符串轉化成數組 secretBytes = MessageDigest.getInstance("md5").digest( plainText.getBytes()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("找不到md5實例"); } String md5code = new BigInteger(1, secretBytes).toString(16);
for (int i = 0; i < 32 - md5code.length(); i++) { md5code = "0" + md5code; } return md5code; } /* //和數據庫的加密一樣,同一個字符串通過md5加密,結果是一樣的 public static void main(String[] args) { System.out.println(md5("123")); }*/ }
package com.louis.web.servlet;

import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import com.louis.domain.User; import com.louis.myconvertor.MyConverter; import com.louis.service.UserService; import com.louis.service.impl.UserServiceImpl; import com.louis.utils.MD5Utils; import com.louis.utils.UUIDUtils; /** * 和用戶相關的servlet */ public class UserServlet extends BaseServlet { public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("userServlet的add方法執行了"); return null; } //調轉到註冊頁面 public String registUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return "/jsp/register.jsp"; } //完成註冊 public String regist(HttpServletRequest request,HttpServletResponse response) throws Exception { //1封裝數據 User user = new User(); //註冊自定義轉化器 ConvertUtils.register(new MyConverter(), Date.class); BeanUtils.populate(user, request.getParameterMap()); //1.1設置用戶id user.setUid(UUIDUtils.getId()); //1.2設置激活碼 user.setCode(UUIDUtils.getCode()); //1.3加密密碼 user.setPassword(MD5Utils.md5(user.getPassword())); //2調用service完成註冊 UserService service = new UserServiceImpl(); service.regist(user); //頁面請求轉發 request.setAttribute("msg", "用戶已註冊,請去郵箱激活"); return "/jsp/msg.jsp"; } }

技術分享

(五)密碼加密