JAVA的Md5工具类

来源:互联网 发布:网络运营托管 编辑:程序博客网 时间:2024/06/10 13:00

原文地址:http://blog.csdn.net/u014653197/article/details/56841468

必须要的jar:


[html] view plain copy
  1. <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->  
  2. <dependency>  
  3.     <groupId>com.google.guava</groupId>  
  4.     <artifactId>guava</artifactId>  
  5.     <version>19.0</version>  
  6. </dependency>  
  7.   
  8. <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->  
  9. <dependency>  
  10.     <groupId>com.google.code.gson</groupId>  
  11.     <artifactId>gson</artifactId>  
  12.     <version>2.8.0</version>  
  13. </dependency>  

工具类代码:


[java] view plain copy
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.lang.reflect.Field;  
  4. import java.nio.charset.Charset;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import com.google.common.collect.Maps;  
  9. import com.google.common.hash.Funnel;  
  10. import com.google.common.hash.HashCode;  
  11. import com.google.common.hash.HashFunction;  
  12. import com.google.common.hash.Hasher;  
  13. import com.google.common.hash.Hashing;  
  14. import com.google.common.hash.PrimitiveSink;  
  15. import com.google.common.io.Files;  
  16. import com.google.gson.Gson;  
  17.   
  18. public class Md5Util {  
  19.     private static HashFunction hf = Hashing.md5();  
  20.     private static Charset defaultCharset = Charset.forName("UTF-8");  
  21.   
  22.     private Md5Util() {  
  23.         throw new AssertionError("不要实例化工具类哦");  
  24.     }  
  25.   
  26.     public static String md5(String data) {  
  27.         HashCode hash = hf.newHasher().putString(data, defaultCharset).hash();  
  28.         return hash.toString();  
  29.     }  
  30.   
  31.     public static String md5(String data, Charset charset, boolean isUpperCase) {  
  32.         HashCode hash = hf.newHasher().putString(data, charset == null ? defaultCharset : charset).hash();  
  33.         return isUpperCase ? hash.toString().toUpperCase() : hash.toString();  
  34.     }  
  35.   
  36.     public static String md5(byte[] bytes, boolean isUpperCase) {  
  37.         HashCode hash = hf.newHasher().putBytes(bytes).hash();  
  38.         return isUpperCase ? hash.toString().toUpperCase() : hash.toString();  
  39.     }  
  40.   
  41.     public static String md5(File sourceFile, boolean isUpperCase) {  
  42.         HashCode hash = hf.newHasher().putObject(sourceFile, new Funnel<File>() {  
  43.   
  44.             private static final long serialVersionUID = 2757585325527511209L;  
  45.   
  46.             @Override  
  47.             public void funnel(File from, PrimitiveSink into) {  
  48.                 try {  
  49.                     into.putBytes(Files.toByteArray(from));  
  50.                 } catch (IOException e) {  
  51.                     throw new RuntimeException(e);  
  52.                 }  
  53.             }  
  54.         }).hash();  
  55.         return isUpperCase ? hash.toString().toUpperCase() : hash.toString();  
  56.     }  
  57.   
  58.     /** 
  59.      * 将其转换为json后,再进行md5 
  60.      * 
  61.      * @param object 数据源可以是任何类型的对象 
  62.      * @param isUpperCase 结果是否大写 
  63.      * @param charset 涉及到字符串时的操作编码,默认是utf-8 
  64.      * @return 
  65.      */  
  66.     public static String md5(Object object, boolean isUpperCase, Charset charset) {  
  67.         Hasher hasher = hf.newHasher();  
  68.         Gson gson = new Gson();  
  69.         String json = gson.toJson(object);  
  70.   
  71.         HashCode hash = hasher.putString(json, charset == null ? defaultCharset : charset).hash();  
  72.         return isUpperCase ? hash.toString().toUpperCase() : hash.toString();  
  73.     }  
  74.   
  75.     /** 
  76.      * @param object 只能是封装了数据的实体类,不可以是map,List等 
  77.      * @param fieldNames 需要参与md5计算的字段属性名,如果该属性也是一个封住数据实体类话,.后跟上具体属性名即可。如:role.level.id 
  78.      * @param isUpperCase 结果是否大写 
  79.      * @param charset 涉及到字符串时的操作编码,默认是utf-8 
  80.      * @return 
  81.      */  
  82.     public static String md5(Object object, List<String> fieldNames, boolean isUpperCase, Charset charset) {  
  83.         HashCode hash = hf.newHasher().putObject(object, new Funnel<Object>() {  
  84.   
  85.             private static final long serialVersionUID = -5236251432355557848L;  
  86.   
  87.             @Override  
  88.             public void funnel(Object from, PrimitiveSink into) {  
  89.   
  90.                 Map<String, Field> allField = getAllField(object);  
  91.   
  92.                 for (String fieldName : fieldNames) {  
  93.   
  94.                     try {  
  95.                         if (fieldName.contains(".")) {  
  96.                             handleDeepField(object, charset, into, allField, fieldName);  
  97.                         } else {  
  98.                             handleField(object, charset, into, allField, fieldName);  
  99.                         }  
  100.                     } catch (Exception e) {  
  101.                         throw new RuntimeException(e);  
  102.                     }  
  103.                 }  
  104.             }  
  105.   
  106.         }).hash();  
  107.         return isUpperCase ? hash.toString().toUpperCase() : hash.toString();  
  108.     }  
  109.   
  110.     private static void handleDeepField(Object tempValue, Charset charset, PrimitiveSink into, Map<String, Field> tempAllField, String fieldName)  
  111.             throws NoSuchFieldException, IllegalAccessException {  
  112.         Field field = null;  
  113.         String[] names = fieldName.split("\\.");  
  114.   
  115.         for (String name : names) {  
  116.             field = tempAllField.get(name);  
  117.             if (field == null) {  
  118.                 throw new NoSuchFieldException(fieldName);  
  119.             }  
  120.             field.setAccessible(true);  
  121.             tempValue = field.get(tempValue);  
  122.             field.setAccessible(false);  
  123.             tempAllField = getAllField(tempValue);  
  124.         }  
  125.   
  126.         stuffFieldValue(tempValue, charset, into);  
  127.     }  
  128.   
  129.     private static void handleField(Object object, Charset charset, PrimitiveSink into, Map<String, Field> allField, String fieldName)  
  130.             throws NoSuchFieldException, IllegalAccessException {  
  131.         Field field = allField.get(fieldName);  
  132.         if (field == null) {  
  133.             throw new NoSuchFieldException(fieldName);  
  134.         }  
  135.   
  136.         field.setAccessible(true);  
  137.         Object tempValue = field.get(object);  
  138.         stuffFieldValue(tempValue, charset, into);  
  139.         field.setAccessible(false);  
  140.     }  
  141.   
  142.     private static void stuffFieldValue(Object value, Charset charset, PrimitiveSink into) throws IllegalAccessException {  
  143.   
  144.         if (value instanceof Integer) {  
  145.             into.putInt((int) value);  
  146.         } else if (value instanceof Long) {  
  147.             into.putLong((long) value);  
  148.         } else if (value instanceof Float) {  
  149.             into.putFloat((float) value);  
  150.         } else if (value instanceof Double) {  
  151.             into.putDouble((double) value);  
  152.         } else if (value instanceof Short) {  
  153.             into.putShort((short) value);  
  154.         } else if (value instanceof Byte) {  
  155.             into.putByte((byte) value);  
  156.         } else if (value instanceof Boolean) {  
  157.             into.putBoolean((boolean) value);  
  158.         } else if (value instanceof Byte) {  
  159.             into.putByte((byte) value);  
  160.         } else if (value instanceof Character) {  
  161.             into.putChar((char) value);  
  162.         } else if (value instanceof String) {  
  163.             into.putString((String) value, charset == null ? defaultCharset : charset);  
  164.         } else {  
  165.             throw new IllegalArgumentException(value.getClass() + " is not basic data type");  
  166.         }  
  167.     }  
  168.   
  169.     private static Map<String, Field> getAllField(Object object) {  
  170.         Map<String, Field> fieldMap = Maps.newHashMap();  
  171.   
  172.         if (object.getClass().getName().equals(Object.class.getName())) {  
  173.             return fieldMap;  
  174.         }  
  175.   
  176.         Class<?> tempClass = object.getClass();  
  177.         Field[] declaredFields = null;  
  178.         while (true) {  
  179.             declaredFields = tempClass.getDeclaredFields();  
  180.             for (Field field : declaredFields) {  
  181.                 fieldMap.put(field.getName(), field);  
  182.             }  
  183.   
  184.             tempClass = tempClass.getSuperclass();  
  185.   
  186.             if (tempClass.getName().equals(Object.class.getName())) {  
  187.                 break;  
  188.             }  
  189.   
  190.         }  
  191.   
  192.         return fieldMap;  
  193.     }  
  194. }