---
title: "MD5加密"
author: "qdexception"
date: "2010-04-29T22:00:53Z"
tags: []
categories: ["编程语言"]
slug: "md5"
draft: false
lastmod: "2010-04-29T22:00:53Z"
id: 656561
url: "https://qdexception.iteye.com/blog/656561"
---

MD5Util:

/**
 * java.security包中的MessageDigest类提供了计算消息摘要的方法， 首先生成对象，执行其update( )方法可 
 以将原始数据传递给该对象，然后执行其digest( )方法即可得到消息摘要。
 */
package org.xxx.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.stereotype.Component;
/**
 * MD5加密
 * @author Administrator
 *
 */
@Component
public class MD5 {
 private MessageDigest messageDigest;
 private String result = "";
 private byte args = null;
 public String getDigestPassWord(String userpass) {
  try {
   // 生成MessageDigest对象,传入所用算法的参数(MD5)
   messageDigest = MessageDigest.getInstance("MD5");
   // 使用 getBytes( )方法生成字符串数组
   messageDigest.update(userpass.getBytes("GBK"));
   // 执行MessageDigest对象的digest( )方法完成计算，计算的结果通过字节类型的数组返回
   args = messageDigest.digest();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
   throw new RuntimeException();
  } catch (UnsupportedEncodingException ee) {
   ee.printStackTrace();
   throw new RuntimeException();
  } finally {
   messageDigest.reset();
  }

  // 将结果转换成字符串
  result = "";// result清空，否则会自动累加！！！
  for (int i = 0; i < args.length; i++) {
   result += Integer.toHexString((0x000000ff & args*) | 0xffffff00)
     .substring(6);
  }
  return result;
 }

}

使用方法:

@Resource private MD5 md5;


this.md5.getDigestPassWord(inputString);