最近碰到一个很头疼的问题,试了很多方式去解决,网上关于DES加密一大堆,五花八门,没有一个标准,大部门关于不一致有一个方法很相近就是
private static byte[] iv = {1,2,3,4,5,6,7,8};
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
// IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return Base64.encode(encryptedData);
}
用这个办法还是不一致,我用了将近一周的时间研究这个东西,后来我终于找到原因了。我把代码贴出来吧,希望大家碰到我一样的问题的时候可以得到一些帮助
public static String encode(String key,byte[] data) throws Exception
{
try
{
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec);
byte[] bytes = cipher.doFinal(data);
return Base64.encode(bytes);
} catch (Exception e)
{
throw new Exception(e);
}
}