Android 常用开发工具类

jopen 9年前

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

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

import java.io.File;  import java.math.BigDecimal;    import android.content.Context;  import android.os.Environment;  import android.text.TextUtils;    /**   * 本应用数据清除管理器   *    *    */  public class DataCleanManager {   /**    * * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * *    *     * @param context    */   public static void cleanInternalCache(Context context) {    deleteFilesByDirectory(context.getCacheDir());   }     /**    * * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * *    *     * @param context    */   public static void cleanDatabases(Context context) {    deleteFilesByDirectory(new File("/data/data/"      + context.getPackageName() + "/databases"));   }     /**    * * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) *    *     * @param context    */   public static void cleanSharedPreference(Context context) {    deleteFilesByDirectory(new File("/data/data/"      + context.getPackageName() + "/shared_prefs"));   }     /**    * * 按名字清除本应用数据库 * *    *     * @param context    * @param dbName    */   public static void cleanDatabaseByName(Context context, String dbName) {    context.deleteDatabase(dbName);   }     /**    * * 清除/data/data/com.xxx.xxx/files下的内容 * *    *     * @param context    */   public static void cleanFiles(Context context) {    deleteFilesByDirectory(context.getFilesDir());   }     /**    * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)    *     * @param context    */   public static void cleanExternalCache(Context context) {    if (Environment.getExternalStorageState().equals(      Environment.MEDIA_MOUNTED)) {     deleteFilesByDirectory(context.getExternalCacheDir());    }   }     /**    * * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * *    *     * @param filePath    * */   public static void cleanCustomCache(String filePath) {    deleteFilesByDirectory(new File(filePath));   }     /**    * * 清除本应用所有的数据 * *    *     * @param context    * @param filepath    */   public static void cleanApplicationData(Context context, String... filepath) {    cleanInternalCache(context);    cleanExternalCache(context);    cleanDatabases(context);    cleanSharedPreference(context);    cleanFiles(context);    if (filepath == null) {     return;    }    for (String filePath : filepath) {     cleanCustomCache(filePath);    }   }     /**    * * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * *    *     * @param directory    */   private static void deleteFilesByDirectory(File directory) {    if (directory.isFile()) {     directory.delete();    } else if (directory != null && directory.exists()      && directory.isDirectory()) {     for (File item : directory.listFiles()) {      deleteFilesByDirectory(item);     }    }   }     // 获取文件   // Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/   // 目录,一般放一些长时间保存的数据   // Context.getExternalCacheDir() -->   // SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据   public static long getFolderSize(File file) throws Exception {    long size = 0;    try {     File[] fileList = file.listFiles();     for (int i = 0; i < fileList.length; i++) {      // 如果下面还有文件      if (fileList[i].isDirectory()) {       size = size + getFolderSize(fileList[i]);      } else {       size = size + fileList[i].length();      }     }    } catch (Exception e) {     e.printStackTrace();    }    return size;   }     /**    * 删除指定目录下文件及目录    *     * @param deleteThisPath    * @param filepath    * @return    */   public static void deleteFolderFile(String filePath, boolean deleteThisPath) {    if (!TextUtils.isEmpty(filePath)) {     try {      File file = new File(filePath);      if (file.isDirectory()) {// 如果下面还有文件       File files[] = file.listFiles();       for (int i = 0; i < files.length; i++) {        deleteFolderFile(files[i].getAbsolutePath(), true);       }      }      if (deleteThisPath) {       if (!file.isDirectory()) {// 如果是文件,删除        file.delete();       } else {// 目录        if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除         file.delete();        }       }      }     } catch (Exception e) {      e.printStackTrace();     }    }   }     /**    * 格式化单位    *     * @param size    * @return    */   public static String getFormatSize(double size) {    double kiloByte = size / 1024;    if (kiloByte < 1) {     return size + "Byte";    }      double megaByte = kiloByte / 1024;    if (megaByte < 1) {     BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));     return result1.setScale(2, BigDecimal.ROUND_HALF_UP)       .toPlainString() + "KB";    }      double gigaByte = megaByte / 1024;    if (gigaByte < 1) {     BigDecimal result2 = new BigDecimal(Double.toString(megaByte));     return result2.setScale(2, BigDecimal.ROUND_HALF_UP)       .toPlainString() + "MB";    }      double teraBytes = gigaByte / 1024;    if (teraBytes < 1) {     BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));     return result3.setScale(2, BigDecimal.ROUND_HALF_UP)       .toPlainString() + "GB";    }    BigDecimal result4 = new BigDecimal(teraBytes);    return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()      + "TB";   }     public static String getCacheSize(File file) throws Exception {    return getFormatSize(getFolderSize(file));   }    }
手机号,邮箱,身份证校验工具类

import java.util.HashMap;  import java.util.regex.Matcher;  import java.util.regex.Pattern;    public class VerificationUtils {     private final static Pattern emailer = Pattern     .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");   private static String _codeError;   // wi =2(n-1)(mod 11)   final static int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4,     2, 1 };   // verify digit   final static int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };   private static int[] ai = new int[18];   private static String[] _areaCode = { "11", "12", "13", "14", "15", "21",     "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42",     "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",     "63", "64", "65", "71", "81", "82", "91" };   private static HashMap<String, Integer> dateMap;   private static HashMap<String, String> areaCodeMap;   static {    dateMap = new HashMap<String, Integer>();    dateMap.put("01", 31);    dateMap.put("02", null);    dateMap.put("03", 31);    dateMap.put("04", 30);    dateMap.put("05", 31);    dateMap.put("06", 30);    dateMap.put("07", 31);    dateMap.put("08", 31);    dateMap.put("09", 30);    dateMap.put("10", 31);    dateMap.put("11", 30);    dateMap.put("12", 31);    areaCodeMap = new HashMap<String, String>();    for (String code : _areaCode) {     areaCodeMap.put(code, null);    }   }     /**    * 验证手机号    *     * @param str    * @return    */   public static boolean isMobile(String str) {    Pattern p = null;    Matcher m = null;    boolean b = false;    p = Pattern.compile("^[1][3,4,5,8,7][0-9]{9}$");    // p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");    m = p.matcher(str);    b = m.matches();    return b;   }     /**    * 验证邮箱    *     * @param email    * @return    */   public static boolean isEmail(String email) {    if (email == null || email.trim().length() == 0)     return false;    return emailer.matcher(email).matches();   }     public static boolean isEmpty(String input) {    if (input == null || "".equals(input))     return true;      for (int i = 0; i < input.length(); i++) {     char c = input.charAt(i);     if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {      return false;     }    }    return true;   }     /**    * 验证位数    * @param code    * @return    */   public static boolean verifyLength(String code) {    int length = code.length();    if (length == 15 || length == 18) {     return true;    } else {     return false;    }   }      /**    * 验证省区    * @param code    * @return    */   public static boolean verifyAreaCode(String code) {    String areaCode = code.substring(0, 2);    if (areaCodeMap.containsKey(areaCode)) {     return true;    } else {     return false;    }   }      /**    * 验证生日    * @param code    * @return    */   public static boolean verifyBirthdayCode(String code) {    String month = code.substring(10, 12);    boolean isEighteenCode = (18 == code.length());    if (!dateMap.containsKey(month)) {     return false;    }    String dayCode = code.substring(12, 14);    Integer day = dateMap.get(month);    String yearCode = code.substring(6, 10);    Integer year = Integer.valueOf(yearCode);      if (day != null) {     if (Integer.valueOf(dayCode) > day || Integer.valueOf(dayCode) < 1) {      return false;     }    } else {     if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {      if (Integer.valueOf(dayCode) > 29        || Integer.valueOf(dayCode) < 1) {       return false;      }     } else {      if (Integer.valueOf(dayCode) > 28        || Integer.valueOf(dayCode) < 1) {       return false;      }     }    }    return true;   }     public static boolean containsAllNumber(String code) {    String str = "";    if (code.length() == 15) {     str = code.substring(0, 15);    } else if (code.length() == 18) {     str = code.substring(0, 17);    }    char[] ch = str.toCharArray();    for (int i = 0; i < ch.length; i++) {     if (!(ch[i] >= '0' && ch[i] <= '9')) {      return false;     }    }    return true;   }           public static boolean verify(String idcard) {    if (!verifyLength(idcard)) {     return false;    }    if (!containsAllNumber(idcard)) {     return false;    }      String eifhteencard = "";    if (idcard.length() == 15) {     eifhteencard = uptoeighteen(idcard);    } else {     eifhteencard = idcard;    }    if (!verifyAreaCode(eifhteencard)) {     return false;    }    if (!verifyBirthdayCode(eifhteencard)) {     return false;    }    if (!verifyMOD(eifhteencard)) {     return false;    }    return true;   }     public static boolean verifyMOD(String code) {    String verify = code.substring(17, 18);    if ("x".equals(verify)) {     code = code.replaceAll("x", "X");     verify = "X";    }    String verifyIndex = getVerify(code);    if (verify.equals(verifyIndex)) {     return true;    }    // int x=17;    // if(code.length()==15){    // x=14;    // }    return false;   }     public static String getVerify(String eightcardid) {    int remaining = 0;      if (eightcardid.length() == 18) {     eightcardid = eightcardid.substring(0, 17);    }      if (eightcardid.length() == 17) {     int sum = 0;     for (int i = 0; i < 17; i++) {      String k = eightcardid.substring(i, i + 1);      ai[i] = Integer.parseInt(k);     }       for (int i = 0; i < 17; i++) {      sum = sum + wi[i] * ai[i];     }     remaining = sum % 11;    }      return remaining == 2 ? "X" : String.valueOf(vi[remaining]);   }     public static String uptoeighteen(String fifteencardid) {    String eightcardid = fifteencardid.substring(0, 6);    eightcardid = eightcardid + "19";    eightcardid = eightcardid + fifteencardid.substring(6, 15);    eightcardid = eightcardid + getVerify(eightcardid);    return eightcardid;   }  }

sharedPreferences封装工具类

import android.content.Context;  import android.content.SharedPreferences;  import android.content.SharedPreferences.Editor;    public class SharedPreferencesUtil {   /**    * 保存在手机里面的文件名    */   private static final String SP_NAME = "sp_name";     public static void setStringParam(Context context, String key, String value) {    SharedPreferences sp = context.getSharedPreferences(SP_NAME,      Context.MODE_PRIVATE);    Editor edit = sp.edit();    edit.putString(key, value);    edit.commit();    key = null;    value = null;    edit = null;    sp = null;    context = null;   }     /**    * 保存字符串数据类型    *     * @param context    * @param keys    * @param values    */   public static void setStringParams(Context context, String[] keys,     String[] values) {    SharedPreferences sp = context.getSharedPreferences(SP_NAME,      Context.MODE_PRIVATE);    Editor edit = sp.edit();    for (int i = 0; i < keys.length; i++) {     edit.putString(keys[i], values[i]);    }    keys = null;    values = null;    edit.commit();    edit = null;    sp = null;    context = null;   }     /**    * 保存所有数据类型 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法    *     * @param context    * @param key    * @param object    */   public static void setParam(Context context, String key, Object object) {      String type = object.getClass().getSimpleName();    SharedPreferences sp = context.getSharedPreferences(SP_NAME,      Context.MODE_PRIVATE);    SharedPreferences.Editor editor = sp.edit();      if ("String".equals(type)) {     editor.putString(key, (String) object);    } else if ("Integer".equals(type)) {     editor.putInt(key, (Integer) object);    } else if ("Boolean".equals(type)) {     editor.putBoolean(key, (Boolean) object);    } else if ("Float".equals(type)) {     editor.putFloat(key, (Float) object);    } else if ("Long".equals(type)) {     editor.putLong(key, (Long) object);    }      key = null;    object = null;    editor.commit();    editor = null;    sp = null;    context = null;   }     /**    * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值    *     * @param context    * @param key    * @param defaultObject    * @return    */   public static Object getParam(Context context, String key,     Object defaultObject) {    String type = defaultObject.getClass().getSimpleName();    SharedPreferences sp = context.getSharedPreferences(SP_NAME,      Context.MODE_PRIVATE);      if ("String".equals(type)) {     return sp.getString(key, (String) defaultObject);    } else if ("Integer".equals(type)) {     return sp.getInt(key, (Integer) defaultObject);    } else if ("Boolean".equals(type)) {     return sp.getBoolean(key, (Boolean) defaultObject);    } else if ("Float".equals(type)) {     return sp.getFloat(key, (Float) defaultObject);    } else if ("Long".equals(type)) {     return sp.getLong(key, (Long) defaultObject);    }      return null;   }    }
Service工具类

import java.util.List;    import android.app.ActivityManager;  import android.content.Context;    /**   * 服务是否运行检测帮助类   *    */  public class ServiceUtil {     /**    * 判断服务是否后台运行    *     * @param context    *            Context    * @param className    *            判断的服务名字    * @return true 在运行 false 不在运行    */   public static boolean isServiceRun(Context mContext, String className) {    boolean isRun = false;    ActivityManager activityManager = (ActivityManager) mContext      .getSystemService(Context.ACTIVITY_SERVICE);    List<ActivityManager.RunningServiceInfo> serviceList = activityManager      .getRunningServices(40);    int size = serviceList.size();    for (int i = 0; i < size; i++) {     if (serviceList.get(i).service.getClassName().equals(className) == true) {      isRun = true;      break;     }    }    return isRun;   }    }

Log日志工具类

import android.util.Log;    /**   * Log显示工具类   */  public class LogUtil {     /**    * 开发    */   private final static int DEVELOP = 0;     /**    * 测试    */   private final static int TEST = 1;     /**    * 上线    */   private final static int ONLINE = 2;     /**    * 当前状态    */   private final static int NOWSTATE = DEVELOP;     public static void info(String msg) {    info("volunteer", msg);   }     public static void info(String TAG, String msg) {    switch (NOWSTATE) {    case DEVELOP:     Log.i(TAG, "develop:---" + msg);     break;    case TEST:     Log.i(TAG, "test:---" + msg);     break;    case ONLINE:       break;      }   }  }

MD5 加密工具类

public final class MD5Utils {      private static final char Digit[] = {          '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',           'a', 'b', 'c', 'd', 'e', 'f'      };      private static final byte PADDING[] = {          -128, 0, 0, 0, 0, 0, 0, 0, 0, 0,           0, 0, 0, 0, 0, 0, 0, 0, 0, 0,           0, 0, 0, 0, 0, 0, 0, 0, 0, 0,           0, 0, 0, 0, 0, 0, 0, 0, 0, 0,           0, 0, 0, 0, 0, 0, 0, 0, 0, 0,           0, 0, 0, 0, 0, 0, 0, 0, 0, 0,           0, 0, 0, 0      };      private static long state[] = new long[4];      private static long count[] = new long[2];      private static byte buffer[] = new byte[64];      private static String digestHexStr;      private static byte digest[] = new byte[16];        private MD5Utils() {      }            /**       * 没有加盐 小写输出       * @param s       * @return       */      public static String toMD5(String s) {          md5Init();          md5Update(s.getBytes(), s.length());          md5Final();          digestHexStr = "";          for(int i = 0; i < 16; i++)              digestHexStr = digestHexStr + byteHEX(digest[i]);            return digestHexStr;      }            private static void md5Init() {          count[0] = 0L;          count[1] = 0L;          state[0] = 0x67452301L;          state[1] = 0xefcdab89L;          state[2] = 0x98badcfeL;          state[3] = 0x10325476L;      }               private static long F(long x, long y, long z) {          return (x & y) | ((~x) & z);       }            private static long G(long x, long y, long z) {          return (x & z) | (y & (~z));       }            private static long H(long x, long y, long z) {          return x ^ y ^ z;      }            private static long I(long x, long y, long z) {          return y ^ (x | (~z));      }        private static long FF(long l, long l1, long l2, long l3,               long l4, long l5, long l6) {          l += F(l1, l2, l3) + l4 + l6;          l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);          l += l1;          return l;      }        private static long GG(long l, long l1, long l2, long l3,               long l4, long l5, long l6) {          l += G(l1, l2, l3) + l4 + l6;          l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);          l += l1;          return l;      }        private static long HH(long l, long l1, long l2, long l3,               long l4, long l5, long l6) {          l += H(l1, l2, l3) + l4 + l6;          l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);          l += l1;          return l;      }        private static long II(long l, long l1, long l2, long l3,               long l4, long l5, long l6) {          l += I(l1, l2, l3) + l4 + l6;          l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);          l += l1;          return l;      }        private static void md5Update(byte abyte0[], int i) {          byte abyte1[] = new byte[64];          int k = (int)(count[0] >>> 3) & 0x3f;          if ((count[0] += i << 3) < (long)(i << 3))              count[1]++;          count[1] += i >>> 29;          int l = 64 - k;          int j;          if (i >= l) {              md5Memcpy(buffer, abyte0, k, 0, l);              md5Transform(buffer);              for(j = l; j + 63 < i; j += 64) {                  md5Memcpy(abyte1, abyte0, 0, j, 64);                  md5Transform(abyte1);              }              k = 0;          } else {              j = 0;          }          md5Memcpy(buffer, abyte0, k, j, i - j);      }        private static void md5Final() {          byte abyte0[] = new byte[8];          Encode(abyte0, count, 8);          int i = (int)(count[0] >>> 3) & 0x3f;          int j = i >= 56 ? 120 - i : 56 - i;          md5Update(PADDING, j);          md5Update(abyte0, 8);          Encode(digest, state, 16);      }        private static void md5Memcpy(byte abyte0[], byte abyte1[], int i, int j, int k) {          for(int l = 0; l < k; l++)              abyte0[i + l] = abyte1[j + l];      }        private static void md5Transform(byte abyte0[]) {          long l = state[0];          long l1 = state[1];          long l2 = state[2];          long l3 = state[3];          long al[] = new long[16];          Decode(al, abyte0, 64);          l = FF(l, l1, l2, l3, al[0], 7L, 0xd76aa478L);          l3 = FF(l3, l, l1, l2, al[1], 12L, 0xe8c7b756L);          l2 = FF(l2, l3, l, l1, al[2], 17L, 0x242070dbL);          l1 = FF(l1, l2, l3, l, al[3], 22L, 0xc1bdceeeL);          l = FF(l, l1, l2, l3, al[4], 7L, 0xf57c0fafL);          l3 = FF(l3, l, l1, l2, al[5], 12L, 0x4787c62aL);          l2 = FF(l2, l3, l, l1, al[6], 17L, 0xa8304613L);          l1 = FF(l1, l2, l3, l, al[7], 22L, 0xfd469501L);          l = FF(l, l1, l2, l3, al[8], 7L, 0x698098d8L);          l3 = FF(l3, l, l1, l2, al[9], 12L, 0x8b44f7afL);          l2 = FF(l2, l3, l, l1, al[10], 17L, 0xffff5bb1L);          l1 = FF(l1, l2, l3, l, al[11], 22L, 0x895cd7beL);          l = FF(l, l1, l2, l3, al[12], 7L, 0x6b901122L);          l3 = FF(l3, l, l1, l2, al[13], 12L, 0xfd987193L);          l2 = FF(l2, l3, l, l1, al[14], 17L, 0xa679438eL);          l1 = FF(l1, l2, l3, l, al[15], 22L, 0x49b40821L);          l = GG(l, l1, l2, l3, al[1], 5L, 0xf61e2562L);          l3 = GG(l3, l, l1, l2, al[6], 9L, 0xc040b340L);          l2 = GG(l2, l3, l, l1, al[11], 14L, 0x265e5a51L);          l1 = GG(l1, l2, l3, l, al[0], 20L, 0xe9b6c7aaL);          l = GG(l, l1, l2, l3, al[5], 5L, 0xd62f105dL);          l3 = GG(l3, l, l1, l2, al[10], 9L, 0x2441453L);          l2 = GG(l2, l3, l, l1, al[15], 14L, 0xd8a1e681L);          l1 = GG(l1, l2, l3, l, al[4], 20L, 0xe7d3fbc8L);          l = GG(l, l1, l2, l3, al[9], 5L, 0x21e1cde6L);          l3 = GG(l3, l, l1, l2, al[14], 9L, 0xc33707d6L);          l2 = GG(l2, l3, l, l1, al[3], 14L, 0xf4d50d87L);          l1 = GG(l1, l2, l3, l, al[8], 20L, 0x455a14edL);          l = GG(l, l1, l2, l3, al[13], 5L, 0xa9e3e905L);          l3 = GG(l3, l, l1, l2, al[2], 9L, 0xfcefa3f8L);          l2 = GG(l2, l3, l, l1, al[7], 14L, 0x676f02d9L);          l1 = GG(l1, l2, l3, l, al[12], 20L, 0x8d2a4c8aL);          l = HH(l, l1, l2, l3, al[5], 4L, 0xfffa3942L);          l3 = HH(l3, l, l1, l2, al[8], 11L, 0x8771f681L);          l2 = HH(l2, l3, l, l1, al[11], 16L, 0x6d9d6122L);          l1 = HH(l1, l2, l3, l, al[14], 23L, 0xfde5380cL);          l = HH(l, l1, l2, l3, al[1], 4L, 0xa4beea44L);          l3 = HH(l3, l, l1, l2, al[4], 11L, 0x4bdecfa9L);          l2 = HH(l2, l3, l, l1, al[7], 16L, 0xf6bb4b60L);          l1 = HH(l1, l2, l3, l, al[10], 23L, 0xbebfbc70L);          l = HH(l, l1, l2, l3, al[13], 4L, 0x289b7ec6L);          l3 = HH(l3, l, l1, l2, al[0], 11L, 0xeaa127faL);          l2 = HH(l2, l3, l, l1, al[3], 16L, 0xd4ef3085L);          l1 = HH(l1, l2, l3, l, al[6], 23L, 0x4881d05L);          l = HH(l, l1, l2, l3, al[9], 4L, 0xd9d4d039L);          l3 = HH(l3, l, l1, l2, al[12], 11L, 0xe6db99e5L);          l2 = HH(l2, l3, l, l1, al[15], 16L, 0x1fa27cf8L);          l1 = HH(l1, l2, l3, l, al[2], 23L, 0xc4ac5665L);          l = II(l, l1, l2, l3, al[0], 6L, 0xf4292244L);          l3 = II(l3, l, l1, l2, al[7], 10L, 0x432aff97L);          l2 = II(l2, l3, l, l1, al[14], 15L, 0xab9423a7L);          l1 = II(l1, l2, l3, l, al[5], 21L, 0xfc93a039L);          l = II(l, l1, l2, l3, al[12], 6L, 0x655b59c3L);          l3 = II(l3, l, l1, l2, al[3], 10L, 0x8f0ccc92L);          l2 = II(l2, l3, l, l1, al[10], 15L, 0xffeff47dL);          l1 = II(l1, l2, l3, l, al[1], 21L, 0x85845dd1L);          l = II(l, l1, l2, l3, al[8], 6L, 0x6fa87e4fL);          l3 = II(l3, l, l1, l2, al[15], 10L, 0xfe2ce6e0L);          l2 = II(l2, l3, l, l1, al[6], 15L, 0xa3014314L);          l1 = II(l1, l2, l3, l, al[13], 21L, 0x4e0811a1L);          l = II(l, l1, l2, l3, al[4], 6L, 0xf7537e82L);          l3 = II(l3, l, l1, l2, al[11], 10L, 0xbd3af235L);          l2 = II(l2, l3, l, l1, al[2], 15L, 0x2ad7d2bbL);          l1 = II(l1, l2, l3, l, al[9], 21L, 0xeb86d391L);          state[0] += l;          state[1] += l1;          state[2] += l2;          state[3] += l3;      }        private static void Encode(byte abyte0[], long al[], int i) {          int j = 0;          for(int k = 0; k < i; k += 4) {              abyte0[k] = (byte)(int)(al[j] & 255L);              abyte0[k + 1] = (byte)(int)(al[j] >>> 8 & 255L);              abyte0[k + 2] = (byte)(int)(al[j] >>> 16 & 255L);              abyte0[k + 3] = (byte)(int)(al[j] >>> 24 & 255L);              j++;          }      }        private static void Decode(long al[], byte abyte0[], int i) {          int j = 0;          for (int k = 0; k < i; k += 4) {              al[j] = b2iu(abyte0[k]) | b2iu(abyte0[k + 1]) << 8 | b2iu(abyte0[k + 2]) << 16 | b2iu(abyte0[k + 3]) << 24;              j++;          }      }        private static long b2iu(byte byte0) {          return byte0 >= 0 ? byte0 : byte0 & 0xff;      }        private static String byteHEX(byte byte0) {          char ac[] = new char[2];          ac[0] = Digit[byte0 >>> 4 & 0xf];          ac[1] = Digit[byte0 & 0xf];          return new String(ac);      }                  public static void main(String[] args) {    System.out.println(toMD5("123456"));   }  }
可逆加密算法工具类

import java.io.UnsupportedEncodingException;    public class Base64Utils {   private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D',     'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',     'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',     'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',     'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',     '4', '5', '6', '7', '8', '9', '+', '/' };   private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,     -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,     60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,     10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,     -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,     38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,     -1, -1 };     /**    * 加密    *     * @param data    * @return    */   public static String encode(byte[] data) {    StringBuffer sb = new StringBuffer();    int len = data.length;    int i = 0;    int b1, b2, b3;    while (i < len) {     b1 = data[i++] & 0xff;     if (i == len) {      sb.append(base64EncodeChars[b1 >>> 2]);      sb.append(base64EncodeChars[(b1 & 0x3) << 4]);      sb.append("==");      break;     }     b2 = data[i++] & 0xff;     if (i == len) {      sb.append(base64EncodeChars[b1 >>> 2]);      sb.append(base64EncodeChars[((b1 & 0x03) << 4)        | ((b2 & 0xf0) >>> 4)]);      sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);      sb.append("=");      break;     }     b3 = data[i++] & 0xff;     sb.append(base64EncodeChars[b1 >>> 2]);     sb.append(base64EncodeChars[((b1 & 0x03) << 4)       | ((b2 & 0xf0) >>> 4)]);     sb.append(base64EncodeChars[((b2 & 0x0f) << 2)       | ((b3 & 0xc0) >>> 6)]);     sb.append(base64EncodeChars[b3 & 0x3f]);    }    return sb.toString();   }     /**    * 解密    *     * @param str    * @return    */   public static byte[] decode(String str) {    try {     return decodePrivate(str);    } catch (UnsupportedEncodingException e) {     e.printStackTrace();    }    return new byte[] {};   }     private static byte[] decodePrivate(String str)     throws UnsupportedEncodingException {    StringBuffer sb = new StringBuffer();    byte[] data = null;    data = str.getBytes("US-ASCII");    int len = data.length;    int i = 0;    int b1, b2, b3, b4;    while (i < len) {       do {      b1 = base64DecodeChars[data[i++]];     } while (i < len && b1 == -1);     if (b1 == -1)      break;       do {      b2 = base64DecodeChars[data[i++]];     } while (i < len && b2 == -1);     if (b2 == -1)      break;     sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));       do {      b3 = data[i++];      if (b3 == 61)       return sb.toString().getBytes("iso8859-1");      b3 = base64DecodeChars[b3];     } while (i < len && b3 == -1);     if (b3 == -1)      break;     sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));       do {      b4 = data[i++];      if (b4 == 61)       return sb.toString().getBytes("iso8859-1");      b4 = base64DecodeChars[b4];     } while (i < len && b4 == -1);     if (b4 == -1)      break;     sb.append((char) (((b3 & 0x03) << 6) | b4));    }    return sb.toString().getBytes("iso8859-1");   }    }

源码下载

来自: http://blog.csdn.net/soul_code/article/details/50297843