Java DES加密和解密简单总结
程序员文章站
2022-03-12 18:54:03
...
DES常用加密模式:
- ECB模式:电子密本方式
- CBC模式:密文分组链接方式
DES加密填充模式:
- NoPadding:算法本身不填充,
- PKCS5Padding:Java和C#默认的填充模式,对加密数据字节长度对8取余为r,如r大于0,则补8-r个字节,字节为8-r的值;如果r等于0,则补8个字节8
- ISO10126Padding
Java代码的实现
- DES加密
//此处的key只能是长度为8的字符串,否则会出现异常
public byte[] DESEncrype(byte[] data, String key) throws Exception {
byte[] keyArr = key.getBytes();
DESKeySpec desKey = new DESKeySpec(keyArr);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secureKey = keyFactory.generateSecret(desKey);
Cipher cipher = Cipher.getInstance("DES/CBC/ISO10126Padding");
//DES算法要求有一个可信任的随机数源,此处使用new IvParameterSpec(keyArr)
//尽量不要使用SecureRandom random = new SecureRandom(),因为可能导致跨语言无法正确解密
cipher.init(Cipher.ENCRYPT_MODE, secureKey, new IvParameterSpec(keyArr));
return cipher.doFinal(data);
}
- DES解密
public static byte[] DESDecrypt(byte[] src, String key) throws Exception {
byte[] keyArr = key.getBytes();
DESKeySpec desKey = new DESKeySpec(keyArr);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secureKey = keyFactory.generateSecret(desKey);
Cipher cipher = Cipher.getInstance("DES/CBC/ISO10126Padding");
cipher.init(Cipher.DECRYPT_MODE, secureKey, new IvParameterSpec(keyArr));
return cipher.doFinal(src);
}
上一篇: Map 理解