加密#
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,太長會截斷,不夠長會拋異常。
解密#
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 儲存
public String bytesToHexString(byte[] data){
return HexBin.encode(data);
}
當然,解密之前先把 Hex String 轉化為 byte []。
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;
}