隨筆:Java 對Excel等文件進行加密、解密

背景:和同行討論時提起對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();

        //用于構建秘密密鑰規(guī)范,以與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)){

            //將字節(jié)數組寫出
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
    
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容