Des是对称加密,加密速度快,但因为是对称加密,容易破解,适用于不是很敏感的数据,但需要简单加密的场景!
本次分享的为Des加解密工具类,有3个工具类,选择自己适用的就好
分别是DesUtil.java DesUtils.java Base64Utils.java DesFileUtils.java
DesUtils.java
@Slf4j
public class DesUtils {
private final static String DES = "DES";
/**
* Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
public static byte[] encryptBytes(byte[] data, byte[] key) throws Exception {
return encrypt(data, key);
}
/**
* Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
public static String encrypt(String data, String key){
byte[] bt = encrypt(data.getBytes(), key.getBytes());
return Base64Utils.encode(bt);
}
/**
* Description 根据键值进行解密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
public static String decrypt(String data, String key) throws Exception {
if (data == null)
return null;
byte[] buf = Base64Utils.decode(data);
byte[] bt = decrypt(buf, key.getBytes());
return new String(bt);
}
/**
* Description 根据键值进行解密
*
* @param data
* @param key
* 加密键byte数组
* @return
*/
public static byte[] decryptBytes(byte[] data, byte[] key){
return decrypt(data, key);
}
/**
* Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key){
byte[] encryptData = null;
try {
SecureRandom sr = new SecureRandom(); // 生成一个可信任的随机数源
DESKeySpec dks = new DESKeySpec(key); // 从原始密钥数据创建DESKeySpec对象
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(DES); // Cipher对象实际完成加密操作
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); // 用密钥初始化Cipher对象
encryptData = cipher.doFinal(data);
}catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException
| NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e){
log.error("des加密异常", e);
}
return encryptData;
}
/**
* Description 根据键值进行解密
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) {
SecureRandom sr = new SecureRandom(); // 生成一个可信任的随机数源
byte[] originData = null;
try {
DESKeySpec dks = new DESKeySpec(key); // 从原始密钥数据创建DESKeySpec对象
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(DES); // Cipher对象实际完成解密操作
cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // 用密钥初始化Cipher对象
originData = cipher.doFinal(data);
}catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException
| NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e){
log.error("des解密异常", e);
}
return originData;
}
public static void main(String[] args) throws Exception {
String s = "nihao你好,。hello!";
String key = "fd6b65de3c826c385edc0705d27bc1bf";
String enStr = encrypt(s, key);
System.out.println("--------enStr=" + enStr);
String deStr = decrypt(enStr, "fd6b65de3c826c385edc0705d27bc1bf");
System.out.println("--------deStr=" + deStr);
}
}
Base64Utils.java
/**
* BASE64编码解码工具包
*/
public class Base64Utils {
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/**
*
* BASE64字符串解码为二进制数据
*
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception{
return Base64.decode(base64.getBytes());
}
/**
*
* 二进制数据编码为BASE64字符串
*
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) {
return new String(Base64.encode(bytes));
}
/**
*
* 将文件编码为BASE64字符串
*
*
* 大文件慎用,可能会导致内存溢出
*
*
* @param filePath 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/**
*
* BASE64字符串转回文件
*
*
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/**
*
* 文件转换为二进制数组
*
*
* @param filePath 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/**
*
* 二进制数据写文件
*
*
* @param bytes 二进制数据
* @param filePath 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
DesFileUtils.java
/**
* @author wcw
* @date 2018年8月7日 下午12:45:25
*
*/
@Log4j
public class DesFileUtils {
/** 加密解密的key */
private Key mKey;
/** 解密的密码 */
private Cipher mDecryptCipher;
/** 加密的密码 */
private Cipher mEncryptCipher;
public DesFileUtils(String key) throws Exception {
synchronized (this) {
initKey(key);
initCipher();
}
}
/**
* 创建一个加密解密的key
*
* @param keyRule
*/
private void initKey(String keyRule) {
byte[] keyByte = keyRule.getBytes();
// 创建一个空的八位数组,默认情况下为0
byte[] byteTemp = new byte[8];
// 将用户指定的规则转换成八位数组
for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
byteTemp[i] = keyByte[i];
}
mKey = new SecretKeySpec(byteTemp, "DES");
}
/***
* 初始化加载密码
*
* @throws Exception
*/
private void initCipher() throws Exception {
mEncryptCipher = Cipher.getInstance("DES");
mEncryptCipher.init(Cipher.ENCRYPT_MODE, mKey);
mDecryptCipher = Cipher.getInstance("DES");
mDecryptCipher.init(Cipher.DECRYPT_MODE, mKey);
}
/**
* 加密文件
*
* @param filePath
* 需要加密的文件路径
* @param savePath
* 加密后保存的位置
*/
public void encryptFile(String filePath, String savePath) {
FileInputStream in = null;
CipherInputStream cin = null;
OutputStream os = null;
try {
in = new FileInputStream(filePath);
cin = new CipherInputStream(in, mEncryptCipher);
os = new FileOutputStream(savePath);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = cin.read(bytes)) > 0) {
os.write(bytes, 0, len);
os.flush();
}
} catch (Exception e) {
log.error("文件加密失败,filePath=" + filePath, e);
throw new RuntimeException("文件加密失败");
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
log.error("输入文件流关闭失败", e);
}
}
if (null != cin) {
try {
cin.close();
} catch (IOException e) {
log.error("加密输入文件流关闭失败", e);
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
log.error("输出文件流关闭失败", e);
}
}
}
}
/**
* 解密文件
*
* @param filePath
* @param outPath
*/
public void decryptFile(String filePath, String outPath) {
FileInputStream in = null;
CipherInputStream cin = null;
OutputStream os = null;
try {
in = new FileInputStream(filePath);
cin = new CipherInputStream(in, mDecryptCipher);
os = new FileOutputStream(outPath);
byte[] buffer = new byte[1024];
int i;
while ((i = cin.read(buffer)) != -1) {
os.write(buffer, 0, i);
}
} catch (Exception e) {
log.error("文件解密失败,filePath=" + filePath, e);
throw new RuntimeException("文件解密失败");
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
log.error("输入文件流关闭失败", e);
}
}
if (null != cin) {
try {
cin.close();
} catch (IOException e) {
log.error("加密输入文件流关闭失败", e);
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
log.error("输出文件流关闭失败", e);
}
}
}
}
/**
* @Title: encryptFile
* @Description: 加密文件
* @param publicKey
* @param sourceFilepath
* @param localFilePath
* 设定文件 @return void 返回类型 @throws
*/
public static void encryptFile(String publicKey, String sourceFilepath, String localFilePath) {
FileOutputStream fos = null;
try {
byte[] data = Base64Utils.fileToByte(sourceFilepath);
byte[] desData = DesUtil.encryptBytes(data,publicKey.getBytes());
fos = new FileOutputStream(new File(localFilePath));
fos.write(desData);
} catch (Exception e) {
log.error("文件加密失败,zaFilePath:" + sourceFilepath, e);
throw new RuntimeException("文件加密失败");
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
log.error("输入文件流关闭失败",e);
}
}
}
}
/**
* @Title: decryptFileFromPartner
* @Description: 解密合作方的文件
* @param sourceFilePath
* @param localFilePath
* 设定文件 @return void 返回类型 @throws
*/
public static void decryptFile(String publicKey, String sourceFilePath, String localFilePath) {
FileOutputStream fos = null;
try {
byte[] data = Base64Utils.fileToByte(sourceFilePath);
byte[] desData = DesUtil.decryptBytes(data,publicKey.getBytes());
fos = new FileOutputStream(new File(localFilePath));
fos.write(desData);
} catch (Exception e) {
log.error("文件解密失败,filePath:" + sourceFilePath, e);
throw new RuntimeException("文件解密失败");
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
log.error("输入文件流关闭失败",e);
}
}
}
}
public static void main(String[] args) throws Exception {
/*DesFileUtils.encryptFile("fd6b65de3c826c385edc0705d27bc1bf","C:\\Users\\chenghao\\Desktop\\electronic_policy_1158576626.pdf", "C:\\Users\\chenghao\\Desktop\\electronic_policy_1158576626_des.pdf");
System.out.println("success");*/
DesFileUtils.decryptFile("fd6b65de3c826c385edc0705d27bc1bf","C:\\Users\\chenghao\\Desktop\\loan_detail_20180905_des.csv", "C:\\Users\\chenghao\\Desktop\\3.csv");
System.out.println("success");
}
}