// 3DES加密 public static String getEnc3DES(String data, String key, String iv) throws Exception { Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("gb2312")); IvParameterSpec ivs = new IvParameterSpec(iv.getBytes("gb2312")); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey securekey = keyFactory.generateSecret(dks); cipher.init(Cipher.ENCRYPT_MODE, securekey, ivs); BASE64Encoder base64Encoder = new BASE64Encoder(); return base64Encoder.encode(cipher.doFinal(data.getBytes("GB2312"))); }
// 3DES解密 public static String getDes3DES(String data, String key, String iv) throws Exception { BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] databyte = base64Decoder.decodeBuffer(data); Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("gb2312")); IvParameterSpec ivs = new IvParameterSpec(iv.getBytes("gb2312")); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey securekey = keyFactory.generateSecret(dks); cipher.init(Cipher.DECRYPT_MODE, securekey, ivs); return new String(cipher.doFinal(databyte), "GB2312"); }
说明:KEY值根据自己需求生成。IV偏移量也可以自己生成,此处只是举个例子。传入的参数data为json类型或其他,传入时.toString()一样就可使用。
public static String KEY = "***"; public static String subStr() throws Exception{ String exOnceByTime = ExDateUtil.exOnceByTime(ExDateUtil.ExDate());//将2019-04-11 14:33:20 变成格式为20190411143320 String IV = StringUtils.substring(exOnceByTime, 0, 8); return IV; } //解密数据 public static JSONObject decode(JSONObject json) throws Exception{ Object data = json.get("data"); String des3des = getDes3DES(data.toString(), KEY, subStr()); return JSONObject.fromObject(des3des); }