Java学习资料-MD5加密

package indi.yangshenhui.tool;
import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import org.apache.log4j.Logger;
/**
 * 安全相关的工具类,包括各种加密算法
 * 
 * @author yangshenhui
 */
public class SecureUtil {
 private static final Logger LOGGER = Logger.getLogger(SecureUtil.class);
 /**
  * 把字节数组转成16进位制数
  * 
  * @param bytes
  * @return
  */
 public static String bytes2Hex(byte[] bytes) {
  StringBuilder md5str = new StringBuilder();
  // 把数组每一字节换成16进制连成md5字符串
  int digital = 0;
  for (int i = 0; i < bytes.length; i++) {
   digital = bytes[i];
   if (digital < 0) {
    digital += 256;
   }
   if (digital < 16) {
    md5str.append("0");
   }
   md5str.append(Integer.toHexString(digital));
  }
  // toUpperCase方法返回一个字符串,该字符串中的所有字母都被转化为大写字母
  return md5str.toString().toUpperCase();
 }
 /**
  * 把字节数组转换成md5
  * 
  * @param bytes
  * @return
  */
 public static String bytes2MD5(byte[] bytes) {
  String md5str = "";
  try {
   // 创建一个提供信息摘要算法的对象,初始化为md5算法对象
   MessageDigest md = MessageDigest.getInstance("MD5");
   // 计算后获得字节数组
   byte[] temp = md.digest(bytes);
   // 把数组每一字节换成16进制连成md5字符串
   md5str = bytes2Hex(temp);
  } catch (Exception e) {
   LOGGER.error(e.getMessage(), e);
  }
  return md5str;
 }
 /**
  * 把字符串转换成md5
  * 
  * @param s
  * @return
  */
 public static String string2MD5(String s) {
  return bytes2MD5(s.getBytes());
 }
 /**
  * 把文件转成md5字符串
  * 
  * @param file
  * @return
  */
 public static String file2MD5(File file) {
  if (file == null) {
   return null;
  }
  if (file.exists() == false) {
   return null;
  }
  if (file.isFile() == false) {
   return null;
  }
  FileInputStream fis = null;
  try {
   // 创建一个提供信息摘要算法的对象,初始化为md5算法对象
   MessageDigest md = MessageDigest.getInstance("MD5");
   fis = new FileInputStream(file);
   byte[] temp = new byte[1024];
   int l = 0;
   while (true) {
    l = fis.read(temp, 0, temp.length);
    if (l == -1) {
     break;
    }
    // 每次循环读取一定的字节都更新
    md.update(temp, 0, l);
   }
   // 关闭流
   fis.close();
   // 返回md5字符串
   return bytes2Hex(md.digest());
  } catch (Exception e) {
   System.out.println(e);
   LOGGER.error(e.getMessage(), e);
  }
  return null;
 }
}

你可能感兴趣的:(Java学习资料-MD5加密)