zoukankan      html  css  js  c++  java
  • MD5 Hashing in Java,Written by dimport

    A wrapper for Java's MD5 class that makes life a little easier.

    This class lets you produce an MD5 hashcode for some binary data. It is useful for storing passwords in databases or file systems, or for checking the validity of downloaded files. It also provides an example of the singleton design pattern.

     import java.security.*;
     
     public class MD5
     {
     
       private MessageDigest md = null;
       static private MD5 md5 = null;
       private static final char[] hexChars ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
     
       /**
        * Constructor is private so you must use the getInstance method
        */
       private MD5() throws NoSuchAlgorithmException
       {
         md = MessageDigest.getInstance("MD5");
       }
     
     
       /**
       * This returns the singleton instance
       */
      public static MD5 getInstance()throws NoSuchAlgorithmException
       {
         
           if (md5 == null)
           {
             md5 = new MD5();
     
         }
         
         return (md5);
       }
     
       public String hashData(byte[] dataToHash)
     
     {
     
       return hexStringFromBytes((calculateHash(dataToHash)));
       }
     
     
     
     private byte[] calculateHash(byte[] dataToHash)
     
     {
          md.update(dataToHash, 0, dataToHash.length);
     
         return (md.digest());
      }
     
     
     
     public String hexStringFromBytes(byte[] b)
     
     {
     
       String hex = "";
     
       int msb;
     
       int lsb = 0;
         int i;
     
       // MSB maps to idx 0
     
       for (i = 0; i < b.length; i++)
     
       {
     
         msb = ((int)b[i] & 0x000000FF) / 16;
     
         lsb = ((int)b[i] & 0x000000FF) % 16;
           hex = hex + hexChars[msb] + hexChars[lsb];
         }
         return(hex);
       }
     
     
         public static void main(String[] args)
         {
             try
             {
        
            MD5 md = MD5.getInstance();
                 System.out.println(md.hashData("hello".getBytes()));
             }
             catch(NoSuchAlgorithmException e)
             {
                 e.printStackTrace(System.out);
             }
         }
     }

  • 相关阅读:
    python中删除某个元素的3种方法
    研发团队开源管理工具最佳实践
    Cocos2dx游戏开发系列笔记13:一个横版拳击游戏Demo完结篇
    Sunny谈软件架构
    整理部分JS 控件 WEB前端常用的做成Jsp项目,方便今后直接用
    hdu3033I love sneakers! (分组背包,错了很多次)
    Using关键字的用法
    Android webViewj简单处理apk的下载链接
    山寨腾讯“爱消除”游戏之菜单特效
    Apache与Nginx优缺点比较
  • 原文地址:https://www.cnblogs.com/MaxWoods/p/705428.html
Copyright © 2011-2022 走看看