## 加密 ``` java public byte[] encrypt(byte[] data, String key) throws Exception { try{ SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey securekey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, securekey, random); return cipher.doFinal(data); }catch(Throwable e){ e.printStackTrace(); } return null; } ``` `Cipher` 是真正加密的. `key` 的长度应该是8,太长会截断,不够长会抛异常。 ## 解密 ``` java public byte[] decrypt(byte[] data, String key) throws Exception { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey securekey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, securekey, random); return cipher.doFinal(data); } ``` ## Hex String 加密后的数据(byte[])可以转化为 Hex String 储存 ``` java public String bytesToHexString(byte[] data){ return HexBin.encode(data); } ``` 当然,解密之前先吧Hex String 转化为byte[]。 ``` java public byte[] hexStringToBytes(String hexString){ byte[] bytes = new byte[hexString.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16); } return bytes; } ```