最近有個項目,因爲參數裏面帶有sql可能是客戶網關對參數做了防侵入,用簡單的base64加密後居然還是不行,決定用AES加密。代碼如下。
/** * 參數加密私鑰 */ static final String paramPrivateKey="3dae12897b044f96";
/** * 加密 * @param sSrc * @return * @throws Exception */ public static String paramEncrypt(String sSrc) throws Exception { if (paramPrivateKey == null) { System.out.print("Key爲空null"); return null; } // 判斷Key是否爲16位 if (paramPrivateKey.length() != 16) { System.out.print("Key長度不是16位"); return null; } byte[] raw = paramPrivateKey.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/補碼方式" cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); return new BASE64Encoder().encode(encrypted);//此處使用BASE64做轉碼功能,同時能起到2次加密的作用。 }
/** * 解密 * @param sSrc * @return * @throws Exception */ public static String paramDecrypt(String sSrc){ try { if(!StringUtils.hasLength(sSrc)){ return ""; } // 判斷Key是否正確 if (paramPrivateKey == null) { System.out.print("Key爲空null"); return null; } // 判斷Key是否爲16位 if (paramPrivateKey.length() != 16) { System.out.print("Key長度不是16位"); return null; } byte[] raw = paramPrivateKey.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密 try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original,"utf-8"); return originalString; } catch (Exception e) { e.printStackTrace(); return null; } } catch (Exception ex) { ex.printStackTrace(); return null; } }
這部分代碼,網上很多,重點是同樣的字符串加密後與在線網站的結果不一致,AES 加密/解密 - 在線工具 (toolhelper.cn)。打開網站看到有很多選項,經過查詢才知道,java生成的都是使用默認參數,參考地址:JAVA實現AES加密、解密 - 奕鋒博客 - 博客園 (cnblogs.com)。