/** * DES加密 * * @param data 加密資料 * @param key 金鑰 * @return 返回加密後的資料 */ public static byte[] desEncrypt(byte[] data, String key, String charset) { try { Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); byte[] k = charset == null || charset.trim().isEmpty() ? key.getBytes() : key.getBytes(charset); SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(k)); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(k)); return cipher.doFinal(data); } catch (Exception e) { return null; } } /** * DES解密 * * @param data 解密資料 * @param key 金鑰 * @return 返回解密後的資料 */ public static String desDecrypt(byte[] data, String key, String charset) { try { Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); byte[] k = charset == null || charset.trim().isEmpty() ? key.getBytes() : key.getBytes(charset); cipher.init(Cipher.DECRYPT_MODE, SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(k)), new IvParameterSpec(k)); if (charset == null || charset.trim().isEmpty()) { return new String(cipher.doFinal(data)); } return new String(cipher.doFinal(data), charset); } catch (Exception e) { return null; } }