文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>java中类似php md5的算法,可以取得文件,字符串和输入流的md5值...

java中类似php md5的算法,可以取得文件,字符串和输入流的md5值...

时间:2010-08-08  来源:motiandashao

java中类似php md5的算法,可以取得文件,字符串和输入流的md5值

import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.security.MessageDigest; public class MD5Utils { private static MD5Utils instance=null; private static MessageDigest md5 =null; private MD5Utils(){}; public static MD5Utils getInstance() { try { instance=new MD5Utils(); md5=MessageDigest.getInstance("MD5"); }catch(Exception e) { return null; } return instance; } public String getStringHash(String source) { String hash=null; try { ByteArrayInputStream in=new ByteArrayInputStream(source.getBytes()); hash=getStreamHash(in); in.close(); }catch (Exception e) { e.printStackTrace(); } return hash; } public String getFileHash(String file) { String hash=null; try { FileInputStream in=new FileInputStream(file); hash=getStreamHash(in); in.close(); }catch (Exception e) { e.printStackTrace(); } return hash; } public String getStreamHash(InputStream stream) { String hash=null; byte[] buffer = new byte[1024]; BufferedInputStream in=null; try { in=new BufferedInputStream(stream); int numRead = 0; while ((numRead = in.read(buffer)) > 0) { md5.update(buffer, 0, numRead); } in.close(); hash=toHexString(md5.digest()); }catch (Exception e) { if(in!=null)try{in.close();}catch (Exception ex) {ex.printStackTrace();} e.printStackTrace(); } return hash; } private String toHexString(byte[] b) { StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i < b.length; i++) { sb.append(hexChar[(b[i] & 0xf0) >>> 4]); sb.append(hexChar[b[i] & 0x0f]); } return sb.toString(); } private char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static void main(String[] args) { System.out.println(MD5Utils.getInstance().getStringHash("yepanpan")); //System.out.println(MD5Utils.getInstance().getFileHash("E:\\software\\2003_Visio_Pro.iso")); } }  

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载