android 开发实用工具代码

在开发中使用一些工具类,能让代码更加简洁,开发效率也更高,下面是我收集的Android中常用的一些开发工具类,如果大家有更好的工具,欢迎私信我。

数据管理的工具类,清理缓存数据

[java]  view plain copy
  1. import java.io.File;  
  2. import java.math.BigDecimal;  
  3.   
  4. import android.content.Context;  
  5. import android.os.Environment;  
  6. import android.text.TextUtils;  
  7.   
  8. /** 
  9.  * 本应用数据清除管理器 
  10.  *  
  11.  *  
  12.  */  
  13. public class DataCleanManager {  
  14.     /** 
  15.      * * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * * 
  16.      *  
  17.      * @param context 
  18.      */  
  19.     public static void cleanInternalCache(Context context) {  
  20.         deleteFilesByDirectory(context.getCacheDir());  
  21.     }  
  22.   
  23.     /** 
  24.      * * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * * 
  25.      *  
  26.      * @param context 
  27.      */  
  28.     public static void cleanDatabases(Context context) {  
  29.         deleteFilesByDirectory(new File("/data/data/"  
  30.                 + context.getPackageName() + "/databases"));  
  31.     }  
  32.   
  33.     /** 
  34.      * * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * 
  35.      *  
  36.      * @param context 
  37.      */  
  38.     public static void cleanSharedPreference(Context context) {  
  39.         deleteFilesByDirectory(new File("/data/data/"  
  40.                 + context.getPackageName() + "/shared_prefs"));  
  41.     }  
  42.   
  43.     /** 
  44.      * * 按名字清除本应用数据库 * * 
  45.      *  
  46.      * @param context 
  47.      * @param dbName 
  48.      */  
  49.     public static void cleanDatabaseByName(Context context, String dbName) {  
  50.         context.deleteDatabase(dbName);  
  51.     }  
  52.   
  53.     /** 
  54.      * * 清除/data/data/com.xxx.xxx/files下的内容 * * 
  55.      *  
  56.      * @param context 
  57.      */  
  58.     public static void cleanFiles(Context context) {  
  59.         deleteFilesByDirectory(context.getFilesDir());  
  60.     }  
  61.   
  62.     /** 
  63.      * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) 
  64.      *  
  65.      * @param context 
  66.      */  
  67.     public static void cleanExternalCache(Context context) {  
  68.         if (Environment.getExternalStorageState().equals(  
  69.                 Environment.MEDIA_MOUNTED)) {  
  70.             deleteFilesByDirectory(context.getExternalCacheDir());  
  71.         }  
  72.     }  
  73.   
  74.     /** 
  75.      * * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * * 
  76.      *  
  77.      * @param filePath 
  78.      * */  
  79.     public static void cleanCustomCache(String filePath) {  
  80.         deleteFilesByDirectory(new File(filePath));  
  81.     }  
  82.   
  83.     /** 
  84.      * * 清除本应用所有的数据 * * 
  85.      *  
  86.      * @param context 
  87.      * @param filepath 
  88.      */  
  89.     public static void cleanApplicationData(Context context, String... filepath) {  
  90.         cleanInternalCache(context);  
  91.         cleanExternalCache(context);  
  92.         cleanDatabases(context);  
  93.         cleanSharedPreference(context);  
  94.         cleanFiles(context);  
  95.         if (filepath == null) {  
  96.             return;  
  97.         }  
  98.         for (String filePath : filepath) {  
  99.             cleanCustomCache(filePath);  
  100.         }  
  101.     }  
  102.   
  103.     /** 
  104.      * * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * * 
  105.      *  
  106.      * @param directory 
  107.      */  
  108.     private static void deleteFilesByDirectory(File directory) {  
  109.         if (directory.isFile()) {  
  110.             directory.delete();  
  111.         } else if (directory != null && directory.exists()  
  112.                 && directory.isDirectory()) {  
  113.             for (File item : directory.listFiles()) {  
  114.                 deleteFilesByDirectory(item);  
  115.             }  
  116.         }  
  117.     }  
  118.   
  119.     // 获取文件  
  120.     // Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/  
  121.     // 目录,一般放一些长时间保存的数据  
  122.     // Context.getExternalCacheDir() -->  
  123.     // SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据  
  124.     public static long getFolderSize(File file) throws Exception {  
  125.         long size = 0;  
  126.         try {  
  127.             File[] fileList = file.listFiles();  
  128.             for (int i = 0; i < fileList.length; i++) {  
  129.                 // 如果下面还有文件  
  130.                 if (fileList[i].isDirectory()) {  
  131.                     size = size + getFolderSize(fileList[i]);  
  132.                 } else {  
  133.                     size = size + fileList[i].length();  
  134.                 }  
  135.             }  
  136.         } catch (Exception e) {  
  137.             e.printStackTrace();  
  138.         }  
  139.         return size;  
  140.     }  
  141.   
  142.     /** 
  143.      * 删除指定目录下文件及目录 
  144.      *  
  145.      * @param deleteThisPath 
  146.      * @param filepath 
  147.      * @return 
  148.      */  
  149.     public static void deleteFolderFile(String filePath, boolean deleteThisPath) {  
  150.         if (!TextUtils.isEmpty(filePath)) {  
  151.             try {  
  152.                 File file = new File(filePath);  
  153.                 if (file.isDirectory()) {// 如果下面还有文件  
  154.                     File files[] = file.listFiles();  
  155.                     for (int i = 0; i < files.length; i++) {  
  156.                         deleteFolderFile(files[i].getAbsolutePath(), true);  
  157.                     }  
  158.                 }  
  159.                 if (deleteThisPath) {  
  160.                     if (!file.isDirectory()) {// 如果是文件,删除  
  161.                         file.delete();  
  162.                     } else {// 目录  
  163.                         if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除  
  164.                             file.delete();  
  165.                         }  
  166.                     }  
  167.                 }  
  168.             } catch (Exception e) {  
  169.                 e.printStackTrace();  
  170.             }  
  171.         }  
  172.     }  
  173.   
  174.     /** 
  175.      * 格式化单位 
  176.      *  
  177.      * @param size 
  178.      * @return 
  179.      */  
  180.     public static String getFormatSize(double size) {  
  181.         double kiloByte = size / 1024;  
  182.         if (kiloByte < 1) {  
  183.             return size + "Byte";  
  184.         }  
  185.   
  186.         double megaByte = kiloByte / 1024;  
  187.         if (megaByte < 1) {  
  188.             BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));  
  189.             return result1.setScale(2, BigDecimal.ROUND_HALF_UP)  
  190.                     .toPlainString() + "KB";  
  191.         }  
  192.   
  193.         double gigaByte = megaByte / 1024;  
  194.         if (gigaByte < 1) {  
  195.             BigDecimal result2 = new BigDecimal(Double.toString(megaByte));  
  196.             return result2.setScale(2, BigDecimal.ROUND_HALF_UP)  
  197.                     .toPlainString() + "MB";  
  198.         }  
  199.   
  200.         double teraBytes = gigaByte / 1024;  
  201.         if (teraBytes < 1) {  
  202.             BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));  
  203.             return result3.setScale(2, BigDecimal.ROUND_HALF_UP)  
  204.                     .toPlainString() + "GB";  
  205.         }  
  206.         BigDecimal result4 = new BigDecimal(teraBytes);  
  207.         return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()  
  208.                 + "TB";  
  209.     }  
  210.   
  211.     public static String getCacheSize(File file) throws Exception {  
  212.         return getFormatSize(getFolderSize(file));  
  213.     }  
  214.   
  215. }  
手机号,邮箱,身份证校验工具类

[java]  view plain copy
  1. import java.util.HashMap;  
  2. import java.util.regex.Matcher;  
  3. import java.util.regex.Pattern;  
  4.   
  5. public class VerificationUtils {  
  6.   
  7.     private final static Pattern emailer = Pattern  
  8.             .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");  
  9.     private static String _codeError;  
  10.     // wi =2(n-1)(mod 11)  
  11.     final static int[] wi = { 791058421637910584,  
  12.             21 };  
  13.     // verify digit  
  14.     final static int[] vi = { 10'X'98765432 };  
  15.     private static int[] ai = new int[18];  
  16.     private static String[] _areaCode = { "11""12""13""14""15""21",  
  17.             "22""23""31""32""33""34""35""36""37""41""42",  
  18.             "43""44""45""46""50""51""52""53""54""61""62",  
  19.             "63""64""65""71""81""82""91" };  
  20.     private static HashMap<String, Integer> dateMap;  
  21.     private static HashMap<String, String> areaCodeMap;  
  22.     static {  
  23.         dateMap = new HashMap<String, Integer>();  
  24.         dateMap.put("01"31);  
  25.         dateMap.put("02"null);  
  26.         dateMap.put("03"31);  
  27.         dateMap.put("04"30);  
  28.         dateMap.put("05"31);  
  29.         dateMap.put("06"30);  
  30.         dateMap.put("07"31);  
  31.         dateMap.put("08"31);  
  32.         dateMap.put("09"30);  
  33.         dateMap.put("10"31);  
  34.         dateMap.put("11"30);  
  35.         dateMap.put("12"31);  
  36.         areaCodeMap = new HashMap<String, String>();  
  37.         for (String code : _areaCode) {  
  38.             areaCodeMap.put(code, null);  
  39.         }  
  40.     }  
  41.   
  42.     /** 
  43.      * 验证手机号 
  44.      *  
  45.      * @param str 
  46.      * @return 
  47.      */  
  48.     public static boolean isMobile(String str) {  
  49.         Pattern p = null;  
  50.         Matcher m = null;  
  51.         boolean b = false;  
  52.         p = Pattern.compile("^[1][3,4,5,8,7][0-9]{9}$");  
  53.         // p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");  
  54.         m = p.matcher(str);  
  55.         b = m.matches();  
  56.         return b;  
  57.     }  
  58.   
  59.     /** 
  60.      * 验证邮箱 
  61.      *  
  62.      * @param email 
  63.      * @return 
  64.      */  
  65.     public static boolean isEmail(String email) {  
  66.         if (email == null || email.trim().length() == 0)  
  67.             return false;  
  68.         return emailer.matcher(email).matches();  
  69.     }  
  70.   
  71.     public static boolean isEmpty(String input) {  
  72.         if (input == null || "".equals(input))  
  73.             return true;  
  74.   
  75.         for (int i = 0; i < input.length(); i++) {  
  76.             char c = input.charAt(i);  
  77.             if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {  
  78.                 return false;  
  79.             }  
  80.         }  
  81.         return true;  
  82.     }  
  83.   
  84.     /** 
  85.      * 验证位数 
  86.      * @param code 
  87.      * @return 
  88.      */  
  89.     public static boolean verifyLength(String code) {  
  90.         int length = code.length();  
  91.         if (length == 15 || length == 18) {  
  92.             return true;  
  93.         } else {  
  94.             return false;  
  95.         }  
  96.     }  
  97.       
  98.     /** 
  99.      * 验证省区 
  100.      * @param code 
  101.      * @return 
  102.      */  
  103.     public static boolean verifyAreaCode(String code) {  
  104.         String areaCode = code.substring(02);  
  105.         if (areaCodeMap.containsKey(areaCode)) {  
  106.             return true;  
  107.         } else {  
  108.             return false;  
  109.         }  
  110.     }  
  111.       
  112.     /** 
  113.      * 验证生日 
  114.      * @param code 
  115.      * @return 
  116.      */  
  117.     public static boolean verifyBirthdayCode(String code) {  
  118.         String month = code.substring(1012);  
  119.         boolean isEighteenCode = (18 == code.length());  
  120.         if (!dateMap.containsKey(month)) {  
  121.             return false;  
  122.         }  
  123.         String dayCode = code.substring(1214);  
  124.         Integer day = dateMap.get(month);  
  125.         String yearCode = code.substring(610);  
  126.         Integer year = Integer.valueOf(yearCode);  
  127.   
  128.         if (day != null) {  
  129.             if (Integer.valueOf(dayCode) > day || Integer.valueOf(dayCode) < 1) {  
  130.                 return false;  
  131.             }  
  132.         } else {  
  133.             if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {  
  134.                 if (Integer.valueOf(dayCode) > 29  
  135.                         || Integer.valueOf(dayCode) < 1) {  
  136.                     return false;  
  137.                 }  
  138.             } else {  
  139.                 if (Integer.valueOf(dayCode) > 28  
  140.                         || Integer.valueOf(dayCode) < 1) {  
  141.                     return false;  
  142.                 }  
  143.             }  
  144.         }  
  145.         return true;  
  146.     }  
  147.   
  148.     public static boolean containsAllNumber(String code) {  
  149.         String str = "";  
  150.         if (code.length() == 15) {  
  151.             str = code.substring(015);  
  152.         } else if (code.length() == 18) {  
  153.             str = code.substring(017);  
  154.         }  
  155.         char[] ch = str.toCharArray();  
  156.         for (int i = 0; i < ch.length; i++) {  
  157.             if (!(ch[i] >= '0' && ch[i] <= '9')) {  
  158.                 return false;  
  159.             }  
  160.         }  
  161.         return true;  
  162.     }  
  163.   
  164.        
  165.   
  166.     public static boolean verify(String idcard) {  
  167.         if (!verifyLength(idcard)) {  
  168.             return false;  
  169.         }  
  170.         if (!containsAllNumber(idcard)) {  
  171.             return false;  
  172.         }  
  173.   
  174.         String eifhteencard = "";  
  175.         if (idcard.length() == 15) {  
  176.             eifhteencard = uptoeighteen(idcard);  
  177.         } else {  
  178.             eifhteencard = idcard;  
  179.         }  
  180.         if (!verifyAreaCode(eifhteencard)) {  
  181.             return false;  
  182.         }  
  183.         if (!verifyBirthdayCode(eifhteencard)) {  
  184.             return false;  
  185.         }  
  186.         if (!verifyMOD(eifhteencard)) {  
  187.             return false;  
  188.         }  
  189.         return true;  
  190.     }  
  191.   
  192.     public static boolean verifyMOD(String code) {  
  193.         String verify = code.substring(1718);  
  194.         if ("x".equals(verify)) {  
  195.             code = code.replaceAll("x""X");  
  196.             verify = "X";  
  197.         }  
  198.         String verifyIndex = getVerify(code);  
  199.         if (verify.equals(verifyIndex)) {  
  200.             return true;  
  201.         }  
  202.         // int x=17;  
  203.         // if(code.length()==15){  
  204.         // x=14;  
  205.         // }  
  206.         return false;  
  207.     }  
  208.   
  209.     public static String getVerify(String eightcardid) {  
  210.         int remaining = 0;  
  211.   
  212.         if (eightcardid.length() == 18) {  
  213.             eightcardid = eightcardid.substring(017);  
  214.         }  
  215.   
  216.         if (eightcardid.length() == 17) {  
  217.             int sum = 0;  
  218.             for (int i = 0; i < 17; i++) {  
  219.                 String k = eightcardid.substring(i, i + 1);  
  220.                 ai[i] = Integer.parseInt(k);  
  221.             }  
  222.   
  223.             for (int i = 0; i < 17; i++) {  
  224.                 sum = sum + wi[i] * ai[i];  
  225.             }  
  226.             remaining = sum % 11;  
  227.         }  
  228.   
  229.         return remaining == 2 ? "X" : String.valueOf(vi[remaining]);  
  230.     }  
  231.   
  232.     public static String uptoeighteen(String fifteencardid) {  
  233.         String eightcardid = fifteencardid.substring(06);  
  234.         eightcardid = eightcardid + "19";  
  235.         eightcardid = eightcardid + fifteencardid.substring(615);  
  236.         eightcardid = eightcardid + getVerify(eightcardid);  
  237.         return eightcardid;  
  238.     }  
  239. }  

sharedPreferences封装工具类

[java]  view plain copy
  1. import android.content.Context;  
  2. import android.content.SharedPreferences;  
  3. import android.content.SharedPreferences.Editor;  
  4.   
  5. public class SharedPreferencesUtil {  
  6.     /** 
  7.      * 保存在手机里面的文件名 
  8.      */  
  9.     private static final String SP_NAME = "sp_name";  
  10.   
  11.     public static void setStringParam(Context context, String key, String value) {  
  12.         SharedPreferences sp = context.getSharedPreferences(SP_NAME,  
  13.                 Context.MODE_PRIVATE);  
  14.         Editor edit = sp.edit();  
  15.         edit.putString(key, value);  
  16.         edit.commit();  
  17.         key = null;  
  18.         value = null;  
  19.         edit = null;  
  20.         sp = null;  
  21.         context = null;  
  22.     }  
  23.   
  24.     /** 
  25.      * 保存字符串数据类型 
  26.      *  
  27.      * @param context 
  28.      * @param keys 
  29.      * @param values 
  30.      */  
  31.     public static void setStringParams(Context context, String[] keys,  
  32.             String[] values) {  
  33.         SharedPreferences sp = context.getSharedPreferences(SP_NAME,  
  34.                 Context.MODE_PRIVATE);  
  35.         Editor edit = sp.edit();  
  36.         for (int i = 0; i < keys.length; i++) {  
  37.             edit.putString(keys[i], values[i]);  
  38.         }  
  39.         keys = null;  
  40.         values = null;  
  41.         edit.commit();  
  42.         edit = null;  
  43.         sp = null;  
  44.         context = null;  
  45.     }  
  46.   
  47.     /** 
  48.      * 保存所有数据类型 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 
  49.      *  
  50.      * @param context 
  51.      * @param key 
  52.      * @param object 
  53.      */  
  54.     public static void setParam(Context context, String key, Object object) {  
  55.   
  56.         String type = object.getClass().getSimpleName();  
  57.         SharedPreferences sp = context.getSharedPreferences(SP_NAME,  
  58.                 Context.MODE_PRIVATE);  
  59.         SharedPreferences.Editor editor = sp.edit();  
  60.   
  61.         if ("String".equals(type)) {  
  62.             editor.putString(key, (String) object);  
  63.         } else if ("Integer".equals(type)) {  
  64.             editor.putInt(key, (Integer) object);  
  65.         } else if ("Boolean".equals(type)) {  
  66.             editor.putBoolean(key, (Boolean) object);  
  67.         } else if ("Float".equals(type)) {  
  68.             editor.putFloat(key, (Float) object);  
  69.         } else if ("Long".equals(type)) {  
  70.             editor.putLong(key, (Long) object);  
  71.         }  
  72.   
  73.         key = null;  
  74.         object = null;  
  75.         editor.commit();  
  76.         editor = null;  
  77.         sp = null;  
  78.         context = null;  
  79.     }  
  80.   
  81.     /** 
  82.      * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 
  83.      *  
  84.      * @param context 
  85.      * @param key 
  86.      * @param defaultObject 
  87.      * @return 
  88.      */  
  89.     public static Object getParam(Context context, String key,  
  90.             Object defaultObject) {  
  91.         String type = defaultObject.getClass().getSimpleName();  
  92.         SharedPreferences sp = context.getSharedPreferences(SP_NAME,  
  93.                 Context.MODE_PRIVATE);  
  94.   
  95.         if ("String".equals(type)) {  
  96.             return sp.getString(key, (String) defaultObject);  
  97.         } else if ("Integer".equals(type)) {  
  98.             return sp.getInt(key, (Integer) defaultObject);  
  99.         } else if ("Boolean".equals(type)) {  
  100.             return sp.getBoolean(key, (Boolean) defaultObject);  
  101.         } else if ("Float".equals(type)) {  
  102.             return sp.getFloat(key, (Float) defaultObject);  
  103.         } else if ("Long".equals(type)) {  
  104.             return sp.getLong(key, (Long) defaultObject);  
  105.         }  
  106.   
  107.         return null;  
  108.     }  
  109.   
  110. }  
Service工具类

[java]  view plain copy
  1. import java.util.List;  
  2.   
  3. import android.app.ActivityManager;  
  4. import android.content.Context;  
  5.   
  6. /** 
  7.  * 服务是否运行检测帮助类 
  8.  *  
  9.  */  
  10. public class ServiceUtil {  
  11.   
  12.     /** 
  13.      * 判断服务是否后台运行 
  14.      *  
  15.      * @param context 
  16.      *            Context 
  17.      * @param className 
  18.      *            判断的服务名字 
  19.      * @return true 在运行 false 不在运行 
  20.      */  
  21.     public static boolean isServiceRun(Context mContext, String className) {  
  22.         boolean isRun = false;  
  23.         ActivityManager activityManager = (ActivityManager) mContext  
  24.                 .getSystemService(Context.ACTIVITY_SERVICE);  
  25.         List<ActivityManager.RunningServiceInfo> serviceList = activityManager  
  26.                 .getRunningServices(40);  
  27.         int size = serviceList.size();  
  28.         for (int i = 0; i < size; i++) {  
  29.             if (serviceList.get(i).service.getClassName().equals(className) == true) {  
  30.                 isRun = true;  
  31.                 break;  
  32.             }  
  33.         }  
  34.         return isRun;  
  35.     }  
  36.   
  37. }  

Log日志工具类

[java]  view plain copy
  1. import android.util.Log;  
  2.   
  3. /** 
  4.  * Log显示工具类 
  5.  */  
  6. public class LogUtil {  
  7.   
  8.     /** 
  9.      * 开发 
  10.      */  
  11.     private final static int DEVELOP = 0;  
  12.   
  13.     /** 
  14.      * 测试 
  15.      */  
  16.     private final static int TEST = 1;  
  17.   
  18.     /** 
  19.      * 上线 
  20.      */  
  21.     private final static int ONLINE = 2;  
  22.   
  23.     /** 
  24.      * 当前状态 
  25.      */  
  26.     private final static int NOWSTATE = DEVELOP;  
  27.   
  28.     public static void info(String msg) {  
  29.         info("volunteer", msg);  
  30.     }  
  31.   
  32.     public static void info(String TAG, String msg) {  
  33.         switch (NOWSTATE) {  
  34.         case DEVELOP:  
  35.             Log.i(TAG, "develop:---" + msg);  
  36.             break;  
  37.         case TEST:  
  38.             Log.i(TAG, "test:---" + msg);  
  39.             break;  
  40.         case ONLINE:  
  41.   
  42.             break;  
  43.   
  44.         }  
  45.     }  
  46. }  

MD5 加密工具类

[java]  view plain copy
  1. public final class MD5Utils {  
  2.     private static final char Digit[] = {  
  3.         '0''1''2''3''4''5''6''7''8''9',   
  4.         'a''b''c''d''e''f'  
  5.     };  
  6.     private static final byte PADDING[] = {  
  7.         -128000000000,   
  8.         0000000000,   
  9.         0000000000,   
  10.         0000000000,   
  11.         0000000000,   
  12.         0000000000,   
  13.         0000  
  14.     };  
  15.     private static long state[] = new long[4];  
  16.     private static long count[] = new long[2];  
  17.     private static byte buffer[] = new byte[64];  
  18.     private static String digestHexStr;  
  19.     private static byte digest[] = new byte[16];  
  20.   
  21.     private MD5Utils() {  
  22.     }  
  23.       
  24.     /** 
  25.      * 没有加盐 小写输出 
  26.      * @param s 
  27.      * @return 
  28.      */  
  29.     public static String toMD5(String s) {  
  30.         md5Init();  
  31.         md5Update(s.getBytes(), s.length());  
  32.         md5Final();  
  33.         digestHexStr = "";  
  34.         for(int i = 0; i < 16; i++)  
  35.             digestHexStr = digestHexStr + byteHEX(digest[i]);  
  36.   
  37.         return digestHexStr;  
  38.     }  
  39.       
  40.     private static void md5Init() {  
  41.         count[0] = 0L;  
  42.         count[1] = 0L;  
  43.         state[0] = 0x67452301L;  
  44.         state[1] = 0xefcdab89L;  
  45.         state[2] = 0x98badcfeL;  
  46.         state[3] = 0x10325476L;  
  47.     }  
  48.   
  49.      
  50.   
  51.     private static long F(long x, long y, long z) {  
  52.         return (x & y) | ((~x) & z);   
  53.     }  
  54.       
  55.     private static long G(long x, long y, long z) {  
  56.         return (x & z) | (y & (~z));   
  57.     }  
  58.       
  59.     private static long H(long x, long y, long z) {  
  60.         return x ^ y ^ z;  
  61.     }  
  62.       
  63.     private static long I(long x, long y, long z) {  
  64.         return y ^ (x | (~z));  
  65.     }  
  66.   
  67.     private static long FF(long l, long l1, long l2, long l3,   
  68.             long l4, long l5, long l6) {  
  69.         l += F(l1, l2, l3) + l4 + l6;  
  70.         l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);  
  71.         l += l1;  
  72.         return l;  
  73.     }  
  74.   
  75.     private static long GG(long l, long l1, long l2, long l3,   
  76.             long l4, long l5, long l6) {  
  77.         l += G(l1, l2, l3) + l4 + l6;  
  78.         l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);  
  79.         l += l1;  
  80.         return l;  
  81.     }  
  82.   
  83.     private static long HH(long l, long l1, long l2, long l3,   
  84.             long l4, long l5, long l6) {  
  85.         l += H(l1, l2, l3) + l4 + l6;  
  86.         l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);  
  87.         l += l1;  
  88.         return l;  
  89.     }  
  90.   
  91.     private static long II(long l, long l1, long l2, long l3,   
  92.             long l4, long l5, long l6) {  
  93.         l += I(l1, l2, l3) + l4 + l6;  
  94.         l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);  
  95.         l += l1;  
  96.         return l;  
  97.     }  
  98.   
  99.     private static void md5Update(byte abyte0[], int i) {  
  100.         byte abyte1[] = new byte[64];  
  101.         int k = (int)(count[0] >>> 3) & 0x3f;  
  102.         if ((count[0] += i << 3) < (long)(i << 3))  
  103.             count[1]++;  
  104.         count[1] += i >>> 29;  
  105.         int l = 64 - k;  
  106.         int j;  
  107.         if (i >= l) {  
  108.             md5Memcpy(buffer, abyte0, k, 0, l);  
  109.             md5Transform(buffer);  
  110.             for(j = l; j + 63 < i; j += 64) {  
  111.                 md5Memcpy(abyte1, abyte0, 0, j, 64);  
  112.                 md5Transform(abyte1);  
  113.             }  
  114.             k = 0;  
  115.         } else {  
  116.             j = 0;  
  117.         }  
  118.         md5Memcpy(buffer, abyte0, k, j, i - j);  
  119.     }  
  120.   
  121.     private static void md5Final() {  
  122.         byte abyte0[] = new byte[8];  
  123.         Encode(abyte0, count, 8);  
  124.         int i = (int)(count[0] >>> 3) & 0x3f;  
  125.         int j = i >= 56 ? 120 - i : 56 - i;  
  126.         md5Update(PADDING, j);  
  127.         md5Update(abyte0, 8);  
  128.         Encode(digest, state, 16);  
  129.     }  
  130.   
  131.     private static void md5Memcpy(byte abyte0[], byte abyte1[], int i, int j, int k) {  
  132.         for(int l = 0; l < k; l++)  
  133.             abyte0[i + l] = abyte1[j + l];  
  134.     }  
  135.   
  136.     private static void md5Transform(byte abyte0[]) {  
  137.         long l = state[0];  
  138.         long l1 = state[1];  
  139.         long l2 = state[2];  
  140.         long l3 = state[3];  
  141.         long al[] = new long[16];  
  142.         Decode(al, abyte0, 64);  
  143.         l = FF(l, l1, l2, l3, al[0], 7L, 0xd76aa478L);  
  144.         l3 = FF(l3, l, l1, l2, al[1], 12L, 0xe8c7b756L);  
  145.         l2 = FF(l2, l3, l, l1, al[2], 17L, 0x242070dbL);  
  146.         l1 = FF(l1, l2, l3, l, al[3], 22L, 0xc1bdceeeL);  
  147.         l = FF(l, l1, l2, l3, al[4], 7L, 0xf57c0fafL);  
  148.         l3 = FF(l3, l, l1, l2, al[5], 12L, 0x4787c62aL);  
  149.         l2 = FF(l2, l3, l, l1, al[6], 17L, 0xa8304613L);  
  150.         l1 = FF(l1, l2, l3, l, al[7], 22L, 0xfd469501L);  
  151.         l = FF(l, l1, l2, l3, al[8], 7L, 0x698098d8L);  
  152.         l3 = FF(l3, l, l1, l2, al[9], 12L, 0x8b44f7afL);  
  153.         l2 = FF(l2, l3, l, l1, al[10], 17L, 0xffff5bb1L);  
  154.         l1 = FF(l1, l2, l3, l, al[11], 22L, 0x895cd7beL);  
  155.         l = FF(l, l1, l2, l3, al[12], 7L, 0x6b901122L);  
  156.         l3 = FF(l3, l, l1, l2, al[13], 12L, 0xfd987193L);  
  157.         l2 = FF(l2, l3, l, l1, al[14], 17L, 0xa679438eL);  
  158.         l1 = FF(l1, l2, l3, l, al[15], 22L, 0x49b40821L);  
  159.         l = GG(l, l1, l2, l3, al[1], 5L, 0xf61e2562L);  
  160.         l3 = GG(l3, l, l1, l2, al[6], 9L, 0xc040b340L);  
  161.         l2 = GG(l2, l3, l, l1, al[11], 14L, 0x265e5a51L);  
  162.         l1 = GG(l1, l2, l3, l, al[0], 20L, 0xe9b6c7aaL);  
  163.         l = GG(l, l1, l2, l3, al[5], 5L, 0xd62f105dL);  
  164.         l3 = GG(l3, l, l1, l2, al[10], 9L, 0x2441453L);  
  165.         l2 = GG(l2, l3, l, l1, al[15], 14L, 0xd8a1e681L);  
  166.         l1 = GG(l1, l2, l3, l, al[4], 20L, 0xe7d3fbc8L);  
  167.         l = GG(l, l1, l2, l3, al[9], 5L, 0x21e1cde6L);  
  168.         l3 = GG(l3, l, l1, l2, al[14], 9L, 0xc33707d6L);  
  169.         l2 = GG(l2, l3, l, l1, al[3], 14L, 0xf4d50d87L);  
  170.         l1 = GG(l1, l2, l3, l, al[8], 20L, 0x455a14edL);  
  171.         l = GG(l, l1, l2, l3, al[13], 5L, 0xa9e3e905L);  
  172.         l3 = GG(l3, l, l1, l2, al[2], 9L, 0xfcefa3f8L);  
  173.         l2 = GG(l2, l3, l, l1, al[7], 14L, 0x676f02d9L);  
  174.         l1 = GG(l1, l2, l3, l, al[12], 20L, 0x8d2a4c8aL);  
  175.         l = HH(l, l1, l2, l3, al[5], 4L, 0xfffa3942L);  
  176.         l3 = HH(l3, l, l1, l2, al[8], 11L, 0x8771f681L);  
  177.         l2 = HH(l2, l3, l, l1, al[11], 16L, 0x6d9d6122L);  
  178.         l1 = HH(l1, l2, l3, l, al[14], 23L, 0xfde5380cL);  
  179.         l = HH(l, l1, l2, l3, al[1], 4L, 0xa4beea44L);  
  180.         l3 = HH(l3, l, l1, l2, al[4], 11L, 0x4bdecfa9L);  
  181.         l2 = HH(l2, l3, l, l1, al[7], 16L, 0xf6bb4b60L);  
  182.         l1 = HH(l1, l2, l3, l, al[10], 23L, 0xbebfbc70L);  
  183.         l = HH(l, l1, l2, l3, al[13], 4L, 0x289b7ec6L);  
  184.         l3 = HH(l3, l, l1, l2, al[0], 11L, 0xeaa127faL);  
  185.         l2 = HH(l2, l3, l, l1, al[3], 16L, 0xd4ef3085L);  
  186.         l1 = HH(l1, l2, l3, l, al[6], 23L, 0x4881d05L);  
  187.         l = HH(l, l1, l2, l3, al[9], 4L, 0xd9d4d039L);  
  188.         l3 = HH(l3, l, l1, l2, al[12], 11L, 0xe6db99e5L);  
  189.         l2 = HH(l2, l3, l, l1, al[15], 16L, 0x1fa27cf8L);  
  190.         l1 = HH(l1, l2, l3, l, al[2], 23L, 0xc4ac5665L);  
  191.         l = II(l, l1, l2, l3, al[0], 6L, 0xf4292244L);  
  192.         l3 = II(l3, l, l1, l2, al[7], 10L, 0x432aff97L);  
  193.         l2 = II(l2, l3, l, l1, al[14], 15L, 0xab9423a7L);  
  194.         l1 = II(l1, l2, l3, l, al[5], 21L, 0xfc93a039L);  
  195.         l = II(l, l1, l2, l3, al[12], 6L, 0x655b59c3L);  
  196.         l3 = II(l3, l, l1, l2, al[3], 10L, 0x8f0ccc92L);  
  197.         l2 = II(l2, l3, l, l1, al[10], 15L, 0xffeff47dL);  
  198.         l1 = II(l1, l2, l3, l, al[1], 21L, 0x85845dd1L);  
  199.         l = II(l, l1, l2, l3, al[8], 6L, 0x6fa87e4fL);  
  200.         l3 = II(l3, l, l1, l2, al[15], 10L, 0xfe2ce6e0L);  
  201.         l2 = II(l2, l3, l, l1, al[6], 15L, 0xa3014314L);  
  202.         l1 = II(l1, l2, l3, l, al[13], 21L, 0x4e0811a1L);  
  203.         l = II(l, l1, l2, l3, al[4], 6L, 0xf7537e82L);  
  204.         l3 = II(l3, l, l1, l2, al[11], 10L, 0xbd3af235L);  
  205.         l2 = II(l2, l3, l, l1, al[2], 15L, 0x2ad7d2bbL);  
  206.         l1 = II(l1, l2, l3, l, al[9], 21L, 0xeb86d391L);  
  207.         state[0] += l;  
  208.         state[1] += l1;  
  209.         state[2] += l2;  
  210.         state[3] += l3;  
  211.     }  
  212.   
  213.     private static void Encode(byte abyte0[], long al[], int i) {  
  214.         int j = 0;  
  215.         for(int k = 0; k < i; k += 4) {  
  216.             abyte0[k] = (byte)(int)(al[j] & 255L);  
  217.             abyte0[k + 1] = (byte)(int)(al[j] >>> 8 & 255L);  
  218.             abyte0[k + 2] = (byte)(int)(al[j] >>> 16 & 255L);  
  219.             abyte0[k + 3] = (byte)(int)(al[j] >>> 24 & 255L);  
  220.             j++;  
  221.         }  
  222.     }  
  223.   
  224.     private static void Decode(long al[], byte abyte0[], int i) {  
  225.         int j = 0;  
  226.         for (int k = 0; k < i; k += 4) {  
  227.             al[j] = b2iu(abyte0[k]) | b2iu(abyte0[k + 1]) << 8 | b2iu(abyte0[k + 2]) << 16 | b2iu(abyte0[k + 3]) << 24;  
  228.             j++;  
  229.         }  
  230.     }  
  231.   
  232.     private static long b2iu(byte byte0) {  
  233.         return byte0 >= 0 ? byte0 : byte0 & 0xff;  
  234.     }  
  235.   
  236.     private static String byteHEX(byte byte0) {  
  237.         char ac[] = new char[2];  
  238.         ac[0] = Digit[byte0 >>> 4 & 0xf];  
  239.         ac[1] = Digit[byte0 & 0xf];  
  240.         return new String(ac);  
  241.     }  
  242.       
  243.       
  244.     public static void main(String[] args) {  
  245.         System.out.println(toMD5("123456"));  
  246.     }  
  247. }  
可逆加密算法工具类

[java]  view plain copy
  1. import java.io.UnsupportedEncodingException;  
  2.   
  3. public class Base64Utils {  
  4.     private static char[] base64EncodeChars = new char[] { 'A''B''C''D',  
  5.             'E''F''G''H''I''J''K''L''M''N''O''P''Q',  
  6.             'R''S''T''U''V''W''X''Y''Z''a''b''c''d',  
  7.             'e''f''g''h''i''j''k''l''m''n''o''p''q',  
  8.             'r''s''t''u''v''w''x''y''z''0''1''2''3',  
  9.             '4''5''6''7''8''9''+''/' };  
  10.     private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,  
  11.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  
  12.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  
  13.             -1, -1, -1, -162, -1, -1, -1635253545556575859,  
  14.             6061, -1, -1, -1, -1, -1, -1, -10123456789,  
  15.             10111213141516171819202122232425, -1,  
  16.             -1, -1, -1, -1, -1262728293031323334353637,  
  17.             3839404142434445464748495051, -1, -1, -1,  
  18.             -1, -1 };  
  19.   
  20.     /** 
  21.      * 加密 
  22.      *  
  23.      * @param data 
  24.      * @return 
  25.      */  
  26.     public static String encode(byte[] data) {  
  27.         StringBuffer sb = new StringBuffer();  
  28.         int len = data.length;  
  29.         int i = 0;  
  30.         int b1, b2, b3;  
  31.         while (i < len) {  
  32.             b1 = data[i++] & 0xff;  
  33.             if (i == len) {  
  34.                 sb.append(base64EncodeChars[b1 >>> 2]);  
  35.                 sb.append(base64EncodeChars[(b1 & 0x3) << 4]);  
  36.                 sb.append("==");  
  37.                 break;  
  38.             }  
  39.             b2 = data[i++] & 0xff;  
  40.             if (i == len) {  
  41.                 sb.append(base64EncodeChars[b1 >>> 2]);  
  42.                 sb.append(base64EncodeChars[((b1 & 0x03) << 4)  
  43.                         | ((b2 & 0xf0) >>> 4)]);  
  44.                 sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);  
  45.                 sb.append("=");  
  46.                 break;  
  47.             }  
  48.             b3 = data[i++] & 0xff;  
  49.             sb.append(base64EncodeChars[b1 >>> 2]);  
  50.             sb.append(base64EncodeChars[((b1 & 0x03) << 4)  
  51.                     | ((b2 & 0xf0) >>> 4)]);  
  52.             sb.append(base64EncodeChars[((b2 & 0x0f) << 2)  
  53.                     | ((b3 & 0xc0) >>> 6)]);  
  54.             sb.append(base64EncodeChars[b3 & 0x3f]);  
  55.         }  
  56.         return sb.toString();  
  57.     }  
  58.   
  59.     /** 
  60.      * 解密 
  61.      *  
  62.      * @param str 
  63.      * @return 
  64.      */  
  65.     public static byte[] decode(String str) {  
  66.         try {  
  67.             return decodePrivate(str);  
  68.         } catch (UnsupportedEncodingException e) {  
  69.             e.printStackTrace();  
  70.         }  
  71.         return new byte[] {};  
  72.     }  
  73.   
  74.     private static byte[] decodePrivate(String str)  
  75.             throws UnsupportedEncodingException {  
  76.         StringBuffer sb = new StringBuffer();  
  77.         byte[] data = null;  
  78.         data = str.getBytes("US-ASCII");  
  79.         int len = data.length;  
  80.         int i = 0;  
  81.         int b1, b2, b3, b4;  
  82.         while (i < len) {  
  83.   
  84.             do {  
  85.                 b1 = base64DecodeChars[data[i++]];  
  86.             } while (i < len && b1 == -1);  
  87.             if (b1 == -1)  
  88.                 break;  
  89.   
  90.             do {  
  91.                 b2 = base64DecodeChars[data[i++]];  
  92.             } while (i < len && b2 == -1);  
  93.             if (b2 == -1)  
  94.                 break;  
  95.             sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));  
  96.   
  97.             do {  
  98.                 b3 = data[i++];  
  99.                 if (b3 == 61)  
  100.                     return sb.toString().getBytes("iso8859-1");  
  101.                 b3 = base64DecodeChars[b3];  
  102.             } while (i < len && b3 == -1);  
  103.             if (b3 == -1)  
  104.                 break;  
  105.             sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));  
  106.   
  107.             do {  
  108.                 b4 = data[i++];  
  109.                 if (b4 == 61)  
  110.                     return sb.toString().getBytes("iso8859-1");  
  111.                 b4 = base64DecodeChars[b4];  
  112.             } while (i < len && b4 == -1);  
  113.             if (b4 == -1)  
  114.                 break;  
  115.             sb.append((char) (((b3 & 0x03) << 6) | b4));  
  116.         }  
  117.         return sb.toString().getBytes("iso8859-1");  
  118.     }  
  119.   
  120. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值