package com.util; import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * AES加密工具類 * @author xWang * @Date 2019-08-27 */ public class AesEncodeUtil { //偏移量 public static final String VIPARA = "1234567876543210"; //AES 為16bytes. DES 為8bytes //編碼方式 public static final String CODE_TYPE = "UTF-8"; //public static final String CODE_TYPE = "GBK"; //填充類型 public static final String AES_TYPE = "AES/ECB/PKCS5Padding"; //public static final String AES_TYPE = "AES/ECB/PKCS7Padding"; //此類型 加密內容,密鑰必須為16字節的倍數位,否則拋異常,需要字節補全再進行加密 //public static final String AES_TYPE = "AES/ECB/NoPadding"; //java 不支持ZeroPadding //public static final String AES_TYPE = "AES/CBC/ZeroPadding"; //私鑰 private static final String AES_KEY="1111222233334444"; //AES固定格式為128/192/256 bits.即:16/24/32bytes。DES固定格式為128bits,即8bytes。 //字符補全 private static final String[] consult = new String[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G"}; /** * 加密 * * @param cleartext * @return */ public static String encrypt(String cleartext) { //加密方式: AES128(CBC/PKCS5Padding) + Base64, 私鑰:1111222233334444 try { IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes()); //兩個參數,第一個為私鑰字節數組, 第二個為加密方式 AES或者DES SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(), "AES"); //實例化加密類,參數為加密方式,要寫全 Cipher cipher = Cipher.getInstance(AES_TYPE); //PKCS5Padding比PKCS7Padding效率高,PKCS7Padding可支持IOS加解密 //初始化,此方法可以采用三種方式,按加密算法要求來添加。(1)無第三個參數(2)第三個參數為SecureRandom random = new SecureRandom();中random對象,隨機數。(AES不可采用這種方法)(3)采用此代碼中的IVParameterSpec //加密時使用:ENCRYPT_MODE; 解密時使用:DECRYPT_MODE; cipher.init(Cipher.ENCRYPT_MODE, key); //CBC類型的可以在第三個參數傳遞偏移量zeroIv,ECB沒有偏移量 //加密操作,返回加密后的字節數組,然后需要編碼。主要編解碼方式有Base64, HEX, UUE,7bit等等。此處看服務器需要什么編碼方式 byte[] encryptedData = cipher.doFinal(cleartext.getBytes(CODE_TYPE)); return new BASE64Encoder().encode(encryptedData); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 解密 * * @param encrypted * @return */ public static String decrypt(String encrypted) { try { byte[] byteMi = new BASE64Decoder().decodeBuffer(encrypted); IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes()); SecretKeySpec key = new SecretKeySpec( AES_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance(AES_TYPE); //與加密時不同MODE:Cipher.DECRYPT_MODE cipher.init(Cipher.DECRYPT_MODE, key); //CBC類型的可以在第三個參數傳遞偏移量zeroIv,ECB沒有偏移量 byte[] decryptedData = cipher.doFinal(byteMi); return new String(decryptedData, CODE_TYPE); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 測試 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { String content = "你笑起來真好看"; test(content); } public static void test(String content) throws UnsupportedEncodingException{ System.out.println("加密內容:" + content); //字節數 int num = content.getBytes(CODE_TYPE).length; System.out.println("加密內容字節數: " + num); System.out.println("加密內容是否16倍數: " + (num%16 == 0 ? true : false)); //字節補全 if(AES_TYPE.equals("AES/ECB/NoPadding")){ System.out.println(); content = completionCodeFor16Bytes(content); System.out.println("加密內容補全后: "+content); } System.out.println(); // 加密 String encryptResult = encrypt(content); content = new String(encryptResult); System.out.println("加密后:" + content); System.out.println(); // 解密 String decryptResult = decrypt(encryptResult); content = new String(decryptResult); //還原 if(AES_TYPE.equals("AES/ECB/NoPadding")){ System.out.println("解密內容還原前: "+content); content = resumeCodeOf16Bytes(content); } System.out.println("解密完成后:" + content); } //NoPadding //補全字符 public static String completionCodeFor16Bytes(String str) throws UnsupportedEncodingException{ int num = str.getBytes(CODE_TYPE).length; int index = num%16; //進行加密內容補全操作, 加密內容應該為 16字節的倍數, 當不足16*n字節是進行補全, 差一位時 補全16+1位 //補全字符 以 $ 開始,$后一位代表$后補全字符位數,之后全部以0進行補全; if(index != 0){ StringBuffer sbBuffer = new StringBuffer(str); if(16-index == 1){ sbBuffer.append("$" + consult[16-1] + addStr(16-1-1)); }else{ sbBuffer.append("$" + consult[16-index-1] + addStr(16-index-1-1)); } str = sbBuffer.toString(); } return str; } //追加字符 public static String addStr(int num){ StringBuffer sbBuffer = new StringBuffer(""); for (int i = 0; i < num; i++) { sbBuffer.append("0"); } return sbBuffer.toString(); } //還原字符(進行字符判斷) public static String resumeCodeOf16Bytes(String str){ int indexOf = str.lastIndexOf("$"); if(indexOf == -1){ return str; } String trim = str.substring(indexOf+1,indexOf+2).trim(); int num = 0; for (int i = 0; i < consult.length; i++) { if(trim.equals(consult[i])){ num = i; } } if(num == 0){ return str; } return str.substring(0,indexOf).trim(); } }