DES加密的java使用

加密

Copy
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，太长会截断，不够长会抛异常。

解密

Copy
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 储存

Copy
public String bytesToHexString(byte[] data){
return HexBin.encode(data);
}

当然，解密之前先吧 Hex String 转化为 byte []。

Copy
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;
}