无线&移动互联网技术研发

换位思考·····
posts - 19, comments - 53, trackbacks - 0, articles - 283
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

java MD5加密

Posted on 2009-05-12 18:13 Gavin.lee 阅读(307) 评论(0)  编辑  收藏 所属分类: java SE & EE

package com.Gavin.tools.util.jiami;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * MD5 data generate tool class
 * File / String 
 * @author Gavin.lee
 * @date 09-5-12 pm
 *
 */


public class MD5Generator {
 
 private static InputStream createInputStream(File file) {
  InputStream is = null;
  try {
   is = new BufferedInputStream(new FileInputStream(file));
  } catch(Exception e) {
   e.printStackTrace();
  }
  return is;
 }
 
 private static String generateMD5ForFile(File file) {
  InputStream is = createInputStream(file);
  byte[] buf = new byte[4096];
  try {
   MessageDigest md = MessageDigest.getInstance("MD5");
   int count = 0;
   while((count = is.read(buf)) > 0) {
    md.update(buf, 0, count);
   }
   byte[] md5 = md.digest();
   is.close();
   buf = null;
   return md5HashToString(md5);
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return null;
 }
 
 private static String generateMD5(byte[] data, int offset, int len) {
  if(data.length == 0) {
   return "";
  }
  
  try {
   MessageDigest md = MessageDigest.getInstance("MD5");
   md.update(data, offset, len);
   byte[] md5 = md.digest();
   return md5HashToString(md5);
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return null;
 }
 
 private static String md5HashToString(byte[] input) {
  StringBuffer strBuf = new StringBuffer();
  int value;
  for(int i = 0; i < input.length; i++) {
   value = input[i];
   value = value > 0 ? value : value + 256;
   String str = Integer.toHexString(value);
   if(str.length() < 2)
    str = "0" + str;
   strBuf.append(str);
  }
  return strBuf.toString();
 }
 
 public static String getMD5Value(File file) {
  return generateMD5ForFile(file);
 }
 
 public static String getMD5Value(String src) {
  if(src == null) {
   return null;
  }
  if(src == "") {
   return "";
  }
   
  byte[] data = src.getBytes();
  return generateMD5(data, 0, data.length);
 }
 
 public static void main(String[] args) {
  //文件加密
  String file = "c:\\test.txt";
  long tmOrg = System.currentTimeMillis();
  String md5  = getMD5Value(new File(file));
  System.out.println("MD5: " + md5);
  long tmLast = System.currentTimeMillis() - tmOrg;
  System.out.println("Use time :" + tmLast + " ms");
  
  //串加密
  String str = "pass";
  System.out.println(getMD5Value(str));
  str = "password";
  System.out.println(getMD5Value(str));
  str = getMD5Value(str);
  System.out.println(str);
  
 }
}


只有注册用户登录后才能发表评论。


网站导航: