EnDecryptUtil 工具類 1.0 加解密工具類

package com.jfai.kg.kafkacomsu.util;


import java.lang.reflect.Method;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


import lombok.extern.slf4j.Slf4j;


/**  
  * @Package com.jfai.kg.kafkacomsu.util
  * @author Some Unknown Author
  * @mender wanglf
  * @Description: Java加密解密工具  SHA1 MD5 BASE64編碼 AES加密
  * @date 2018年6月30日 下午3:38:21 
  * @version 1.0
  */
@Slf4j
public class EnDecryptUtil {

// 密鑰
private final static String secretKey = "[email protected]";
// 向量
private final static String iv = "01234567";
// 加解密統一使用的編碼方式
private final static String encoding = "utf-8";

// 無需創建對象,所以構造方法暫時私有
private EnDecryptUtil() {}


/**
* 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);
log.debug("encodeBASE64-->" + clazz);
log.debug("encodeMethod-->" + encodeMethod);
// 反射方法 靜態方法執行無需對象
return new String((byte[]) encodeMethod.invoke(null, source.getBytes()));
} catch (ClassNotFoundException e) {
String vm = System.getProperty("java.vm.name");
log.debug(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);
log.debug("encodeBASE64-->" + clazz);
log.debug("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);
log.debug("encodeBASE64-->" + clazz);
log.debug("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;
}
}


/**
* 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);
log.debug("decodeBASE64-->" + clazz);
log.debug("decodeMethod-->" + decodeMethod);
// 反射方法 靜態方法執行無需對象
return new String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes()));
} catch (ClassNotFoundException e) {
String vm = System.getProperty("java.vm.name");
log.debug(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);
log.debug("decodeBASE64-->" + clazz);
log.debug("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);
log.debug("decodeBASE64-->" + clazz);
log.debug("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;
}
}


/**
* 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 (Exception e) {
throw new RuntimeException(e);
}
// 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 (Exception e) {
throw new RuntimeException(e);
}
// 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;
}









public static void main(String[] args) {
// byte[] arr1 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 22 };
// log.info("SHA1 加密 : " + SHA1Bit(arr1));
// log.info("SHA1 解密 : " + SHA1("arr1"));
// log.info("MD5 加密 : " + MD5Bit(arr1));
// log.info("MD5 加密 : " + MD5("arr1"));//
// 54f04b52a75382a157f69457810c41bd
// log.info("BASE64 加密 : " + encodeBASE64("arr1"));
// log.info("BASE64 解密 : " + decodeBASE64(encodeBASE64("arr1")));
// log.info("3DES 加密 : " + d3esEncode("arr1"));
// log.info("d3esDecode(decodeBASE64(encodeBASE64(d3esEncode('arr1'))))
// = "
// + d3esDecode(decodeBASE64(encodeBASE64(d3esEncode("arr1")))));
// log.info("3DES 解密 : " + d3esDecode(d3esEncode("arr1")));
// log.info("AES 加密 : " + encryptBitAES(arr1, "arr1"));
// log.info("AES 解密 : " + decryptBitAES(encryptBitAES(arr1, "arr1"),
// "arr1"));


}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章