天天看點

關于檔案的加密解密

pom.xml引入jar包

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-security</artifactId>
</dependency>
           

下面上代碼

package com.train.cloud.util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * word 檔案加解密util
 */
public class AESUtil {

    public static final String sKey = "123456789abcdefghijklmnopqrstuvwxyz";

    /**
     * 輸入,輸出檔案
     * type=2 解密
     * type=1 加密
     * @param sourceFile
     * @param targetFile
     * @param sKey
     *@param type  @return
     */
    public static File enOrDeFile(File sourceFile, File targetFile, String sKey, int type) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (!targetFile.exists()){
                if (!targetFile.getParentFile().exists()){
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
            }
            if (sourceFile != null){
                inputStream = new FileInputStream(sourceFile);
            }else {
                return null;
            }
            outputStream = new FileOutputStream(targetFile);
            Cipher cipher = initAESCipher(AESUtil.sKey, type);

            CipherInputStream cipherInputStream = null;
            CipherOutputStream cipherOutputStream = null;
            if (Cipher.ENCRYPT_MODE == type) {
                // 建立加密流
                cipherInputStream = new CipherInputStream(inputStream, cipher);
            }else if (Cipher.DECRYPT_MODE == type) {
                // 建立解密流
                cipherOutputStream = new CipherOutputStream(outputStream, cipher);
            }

            byte [] cache = new byte[1024];

            int isread = 0;
            if (Cipher.ENCRYPT_MODE == type) {
                // 加密流寫入檔案
                while ((isread = cipherInputStream.read(cache, 0, cache.length)) != -1) {
                    outputStream.write(cache, 0, isread);
                }
            }else if (Cipher.DECRYPT_MODE == type) {
                // 解密流開始寫入檔案
                while ((isread = inputStream.read(cache, 0, cache.length)) != -1) {
                    cipherOutputStream.write(cache, 0, isread);
                }
            }

            if (cipherInputStream != null) cipherInputStream.close();
            if (cipherOutputStream != null) cipherOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return targetFile;
    }

    public static Cipher initAESCipher(String sKey, int cipherMode) {
        // 建立Key gen
        KeyGenerator generator = null;
        Cipher cipher = null;

        try {
            generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(sKey.getBytes());
            generator.init(128,secureRandom);

            SecretKey secretKey = generator.generateKey();
            byte[] codeFormat = secretKey.getEncoded();

            SecretKeySpec keySpec = new SecretKeySpec(codeFormat, "AES");
            cipher = Cipher.getInstance("AES");
            // 初始化
            cipher.init(cipherMode, keySpec);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return cipher;
    }



    /*public static void main(String[] args) throws Exception{

        File sourceFile = new File("E:\\ppp\\");
        for(File file:sourceFile.listFiles()){

            if (!file.isDirectory()){
                String newPath = file.getParentFile().getAbsolutePath()+"/test/"+file.getName();
                File encrypFile = new File(newPath);
                System.out.print(encrypFile.getAbsolutePath());
                if (!encrypFile.exists()){
                    if (!encrypFile.getParentFile().exists()){
                        encrypFile.getParentFile().mkdirs();
                    }
                    encrypFile.createNewFile();
                }
                enOrDeFile(file,encrypFile,sKey,Cipher.ENCRYPT_MODE);
            }
        }
        *//*File encrypFile = new File("C:\\Users\\Administrator\\Desktop\\實訓平台\\1.docx");
        if (!encrypFile.exists()){
            encrypFile.createNewFile();
        }*//*

        *//*File decrypFile = new File("F:\\1加密.docx");
        if (!decrypFile.exists()){
            decrypFile.createNewFile();
        }*//*

        //加密
        //enOrDeFile(sourceFile,encrypFile,sKey,Cipher.ENCRYPT_MODE);
        //解密
        //enOrDeFile(encrypFile,decrypFile,sKey,Cipher.DECRYPT_MODE);

    }*/



}
      

繼續閱讀