背景:和同行讨论时提起对Excel等文件进行保存时,如何文件泄露后数据被直接看到,讨论了许多种方法,分割存储,打包文件压缩后加密,对文件加密等,于是了解了一下Java这方面的知识,写了一个对文件加密的工具类
package crypto.CipherUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.SecureRandom;
/**
* @description:
* @author: hinotoyk
* @create: 2020-06-25 20:44
**/
public enum EncryptUtils {
ENCRYPT_UTILS;
/**
* 密钥算法
*/
private static final String ALGORITHM = "AES";
/**
* 加解密算法/工作模式/填充方式
*/
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
private static final String SECRET_KEY = "hinotoyk";
public void encrypt(File srcFile,File destFile) throws Exception {
//初始化Cipher,设置是加密Model
Cipher cipher = initCipher(Cipher.ENCRYPT_MODE);
byte[] srcByte = cipher.doFinal(fileToByteArr(srcFile));
byteArrToFile(srcByte,destFile);
}
public void decrypt(File srcFile,File destFile) throws Exception {
//初始化Cipher,设置是解密Model
Cipher cipher = initCipher(Cipher.DECRYPT_MODE);
byte[] srcByte = cipher.doFinal(fileToByteArr(srcFile));
byteArrToFile(srcByte,destFile);
}
/***
* ENCRYPT_MODE = 1;加密
* DECRYPT_MODE = 2;解密
* @param model Cipher的常量,指定Cipher的工作模式
*/
private Cipher initCipher(int model) throws Exception{
//获得AES算法加密的密钥生成
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
//初始化密钥生成器,指定密钥长度为128,指定随机源的种子为指定的密钥SECRET_KEY
keyGenerator.init(128, new SecureRandom(SECRET_KEY.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
//用于构建秘密密钥规范,以与provider无关的方式指定一个密钥
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(model,secretKeySpec);
return cipher;
}
//文件转byte数组
private byte[] fileToByteArr(File file) {
byte[] byteBuff = new byte[1024];
int n = -1;
try(FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024)){
while ((n = fis.read(byteBuff)) !=-1){
bos.write(byteBuff,0,n);
}
return bos.toByteArray();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
//byte数组转文件
private void byteArrToFile(byte[] bytes, File destFile) {
//File dir = new File(filePath);
//// 判断文件目录是否存在
//if (dir.isDirectory() && !dir.exists()) {
// dir.mkdirs();
//}
//if(!destFile.exists()){
// destFile.createNewFile();
//}
try (FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream bos = new BufferedOutputStream(fos)){
//将字节数组写出
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
}