Java加密解密工具(適用於JavaSE/JavaEE/Android)_java

來源:互聯網
上載者:User

本文執行個體為大家分享了一個適用於JavaSE/JavaEE/Android的Java加密解密工具,供大家學習,具體內容如下

package longshu.utils.security; import java.lang.reflect.Method;import java.security.InvalidKeyException;import java.security.Key;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom; import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec; /** * Java加密解密工具. * JavaSE/JavaEE/Android都適用 *  * @author longshu 2016年4月13日 */public class EncryptDecrypt { // 無需建立對象 private EncryptDecrypt() { }  /**  * SHA1加密Bit資料  * @param source byte數組  * @return 加密後的byte數組  */ public static byte[] SHA1Bit(byte[] source) {  try {   MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");   sha1Digest.update(source);   byte targetDigest[] = sha1Digest.digest();   return targetDigest;  } catch (NoSuchAlgorithmException e) {   throw new RuntimeException(e);  } }  /**  * SHA1加密字串資料  * @param source 要加密的字串  * @return 加密後的字串  */ public static String SHA1(String source) {  return byte2HexStr(SHA1Bit(source.getBytes())); }  /**  * MD5加密Bit資料  * @param source byte數組  * @return 加密後的byte數組  */ public static byte[] MD5Bit(byte[] source) {  try {   // 獲得MD5摘要演算法的 MessageDigest對象   MessageDigest md5Digest = MessageDigest.getInstance("MD5");   // 使用指定的位元組更新摘要   md5Digest.update(source);   // 獲得密文   return md5Digest.digest();  } catch (NoSuchAlgorithmException e) {   throw new RuntimeException(e);  } }  /**  * MD5加密字串,32位長  * @param source 要加密的內容  * @return 加密後的內容  */ public static String MD5(String source) {  return byte2HexStr(MD5Bit(source.getBytes())); }  /**  * BASE64編碼  * @param source 要編碼的字串  * @return 編碼過的字串  */ public static String encodeBASE64(String source) {  Class<?> clazz = null;  Method encodeMethod = null;  try {// 優先使用第三方庫   clazz = Class.forName("org.apache.commons.codec.binary.Base64");   encodeMethod = clazz.getMethod("encodeBase64", byte[].class);   System.out.println("encodeBASE64-->" + clazz);   System.out.println("encodeMethod-->" + encodeMethod);   // 反射方法 靜態方法執行無需對象   return new String((byte[]) encodeMethod.invoke(null, source.getBytes()));  } catch (ClassNotFoundException e) {   String vm = System.getProperty("java.vm.name");   System.out.println(vm);   try {    if ("Dalvik".equals(vm)) {// Android     clazz = Class.forName("android.util.Base64");     // byte[] Base64.encode(byte[] input,int flags)     encodeMethod = clazz.getMethod("encode", byte[].class, int.class);     System.out.println("encodeBASE64-->" + clazz);     System.out.println("encodeMethod-->" + encodeMethod);     return new String((byte[]) encodeMethod.invoke(null, source.getBytes(), 0));    } else {// JavaSE/JavaEE     clazz = Class.forName("sun.misc.BASE64Encoder");     encodeMethod = clazz.getMethod("encode", byte[].class);     System.out.println("encodeBASE64-->" + clazz);     System.out.println("encodeMethod-->" + encodeMethod);     return (String) encodeMethod.invoke(clazz.newInstance(), source.getBytes());    }   } catch (ClassNotFoundException e1) {    return null;   } catch (Exception e1) {    return null;   }  } catch (Exception e) {   return null;  }  /*   * Android   * android.util.Base64   */  // return Base64.encodeToString(source, Base64.DEFAULT);  // return new String(Base64.encode(source.getBytes(), Base64.DEFAULT));   /*   * JavaSE/JavaEE   */  // sun.misc.BASE64Encoder  // BASE64Encoder encoder = new BASE64Encoder();  // return encoder.encode(source.getBytes());   // org.apache.commons.codec.binary.Base64  // return new String(Base64.encodeBase64(source.getBytes())); }  /**  * BASE64解碼  * @param encodeSource 編碼過的字串  * @return 編碼前的字串  */ public static String decodeBASE64(String encodeSource) {  Class<?> clazz = null;  Method decodeMethod = null;   try {// 優先使用第三方庫   clazz = Class.forName("org.apache.commons.codec.binary.Base64");   decodeMethod = clazz.getMethod("decodeBase64", byte[].class);   System.out.println("decodeBASE64-->" + clazz);   System.out.println("decodeMethod-->" + decodeMethod);   // 反射方法 靜態方法執行無需對象   return new String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes()));  } catch (ClassNotFoundException e) {   String vm = System.getProperty("java.vm.name");   System.out.println(vm);   try {    if ("Dalvik".equals(vm)) {// Android     clazz = Class.forName("android.util.Base64");     // byte[] Base64.decode(byte[] input, int flags)     decodeMethod = clazz.getMethod("decode", byte[].class, int.class);     System.out.println("decodeBASE64-->" + clazz);     System.out.println("decodeMethod-->" + decodeMethod);     return new String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes(), 0));    } else { // JavaSE/JavaEE     clazz = Class.forName("sun.misc.BASE64Decoder");     decodeMethod = clazz.getMethod("decodeBuffer", String.class);     System.out.println("decodeBASE64-->" + clazz);     System.out.println("decodeMethod-->" + decodeMethod);     return new String((byte[]) decodeMethod.invoke(clazz.newInstance(), encodeSource));    }   } catch (ClassNotFoundException e1) {    return null;   } catch (Exception e1) {    return null;   }  } catch (Exception e) {   return null;  }  /*   * Android   * android.util.Base64   */  // return new  // String(Base64.decode(encodeSource.getBytes(),Base64.DEFAULT));   /*   * JavaSE/JavaEE   */  // sun.misc.BASE64Decoder  // try {  // BASE64Decoder decoder = new BASE64Decoder();  // return new String(decoder.decodeBuffer(encodeSource));  // } catch (IOException e) {  // throw new RuntimeException(e);  // }   // org.apache.commons.codec.binary.Base64  // return new String(Base64.decodeBase64(encodeSource.getBytes())); }  /**  * AES加密  * @param content 待加密的內容  * @param password 加密密碼  * @return  */ public static byte[] encryptBitAES(byte[] content, String password) {  try {   Cipher encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 建立密碼器   encryptCipher.init(Cipher.ENCRYPT_MODE, getKey(password));// 初始化   byte[] result = encryptCipher.doFinal(content);   return result; // 加密  } catch (NoSuchAlgorithmException e) {   e.printStackTrace();  } catch (NoSuchPaddingException e) {   e.printStackTrace();  } catch (InvalidKeyException e) {   e.printStackTrace();  } catch (IllegalBlockSizeException e) {   e.printStackTrace();  } catch (BadPaddingException e) {   e.printStackTrace();  }  return null; }  /**  * AES解密  * @param content 待解密內容  * @param password 解密密鑰  * @return  */ public static byte[] decryptBitAES(byte[] content, String password) {  try {   Cipher decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 建立密碼器   decryptCipher.init(Cipher.DECRYPT_MODE, getKey(password));// 初始化   byte[] result = decryptCipher.doFinal(content);   return result; // 加密結果  } catch (InvalidKeyException e) {   e.printStackTrace();  } catch (NoSuchAlgorithmException e) {   e.printStackTrace();  } catch (NoSuchPaddingException e) {   e.printStackTrace();  } catch (IllegalBlockSizeException e) {   e.printStackTrace();  } catch (BadPaddingException e) {   e.printStackTrace();  }  return null; }  /**  * AES字串加密  * @param content 待加密的內容  * @param password 加密密碼  * @return  */ public static String encryptAES(String content, String password) {  return byte2HexStr(encryptBitAES(content.getBytes(), password)); }  /**  * AES字串解密  * @param content 待解密內容  * @param password 解密密鑰  * @return  */ public static String decryptAES(String content, String password) {  return new String(decryptBitAES(hexStr2Bytes(content), password)); }  /**  * 從指定字串產生密鑰  * @param password 構成該秘鑰的字串  * @return 產生的密鑰  * @throws NoSuchAlgorithmException  */ private static Key getKey(String password) throws NoSuchAlgorithmException {  SecureRandom secureRandom = new SecureRandom(password.getBytes());  // 產生KEY  KeyGenerator kgen = KeyGenerator.getInstance("AES");  kgen.init(128, secureRandom);  SecretKey secretKey = kgen.generateKey();  byte[] enCodeFormat = secretKey.getEncoded();  // 轉換KEY  SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  return key; }  /**  * 將byte數群組轉換為表示16進位值的字串.  * 如:byte[]{8,18}轉換為:0812   * 和 byte[] hexStr2Bytes(String strIn) 互為可逆的轉換過程.  * @param bytes 需要轉換的byte數組  * @return 轉換後的字串  */ public static String byte2HexStr(byte[] bytes) {  int bytesLen = bytes.length;  // 每個byte用兩個字元才能表示,所以字串的長度是數組長度的兩倍  StringBuffer hexString = new StringBuffer(bytesLen * 2);  for (int i = 0; i < bytesLen; i++) {   // 將每個位元組與0xFF進行與運算,然後轉化為10進位,然後藉助於Integer再轉化為16進位   String hex = Integer.toHexString(bytes[i] & 0xFF);   if (hex.length() < 2) {    hexString.append(0);// 如果為1位 前面補個0   }   hexString.append(hex);  }  return hexString.toString(); }  /**  * 將表示16進位值的字串轉換為byte數組,  * 和 String byte2HexStr(byte[] bytes) 互為可逆的轉換過程.  * @param bytes  * @return 轉換後的byte數組  */ public static byte[] hexStr2Bytes(String strIn) {  byte[] arrB = strIn.getBytes();  int iLen = arrB.length;   // 兩個字元表示一個位元組,所以位元組數組長度是字串長度除以2  byte[] arrOut = new byte[iLen / 2];  for (int i = 0; i < iLen; i = i + 2) {   String strTmp = new String(arrB, i, 2);   arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);  }  return arrOut; } }

以上就是本文的全部內容,希望對大家學習java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.