简单DES加密
程序员文章站
2022-03-13 14:52:23
...
- 加密:
/** * @Author HLS * @Description 加密:DES加密、CBC模式、PKCS5Padding填充模式 * @Date 2019/2/22 10:59 * @Param [data 明文,key **] * @return java.lang.String 加密后的结果 **/ public static String encrypt(String data, String key) throws Exception { //设置加密方式为DES加密,CBC模式、PKCS5Padding填充模式 Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8")); //创建一个密匙工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); //设置一个可信任的数据源 IvParameterSpec iv = new IvParameterSpec(key.substring(0, 8).getBytes("UTF-8")); //用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, iv); //获取数据并加密 byte[] bt = cipher.doFinal(data.getBytes("UTF-8")); //由于需要通过网络传输,使用Base64进行编码并且把+号全部转为%2B String strs = new BASE64Encoder().encode(bt).replaceAll("[+]", "%2B"); return strs; }
- 解密:
/**
* @Author HLS
* @Description 解密:DES加密、CBC模式、PKCS5Padding填充模式
* @Date 2019/2/22 11:10
* @Param [data 密文, key **]
* @return java.lang.String 明文
**/
public static String decrypt(String datasource, String key) throws Exception {
//把通过BASE64加密的数据转换回来
byte[] data = new BASE64Decoder().decodeBuffer(datasource.replaceAll("%2B","[+]"));
// 获取可信任的数据源
IvParameterSpec iv = new IvParameterSpec(key.substring(0, 8).getBytes("UTF-8"));
//创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8"));
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象设置解密方式
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
//解密
byte[] bt = cipher.doFinal(data);
//转换成字符串输出
String strs = new String(bt);
return strs;
}