AES128文件内容快速加密

本文采用AES加密方式对文件内容进行加密,AES效率高。

以下是AES的工具类,拿来即可使用,方便快捷

package cn.gs.core.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * 
 */
public class AES {
     private final static Logger logger = LoggerFactory.getLogger(AES.class);
    public static String cKey = "1fc3351d-7b05-440f-8f0b-be4caef0b944";

    /**
     * 加密字符串
     * 
     * @param content  需要加密的内容
     * @param password 密码
     * @return
     */
    public static byte[] encrypt(String content, String sKey) {
        try {
            // 初始化 加密器
            Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
            byte[] byteContent = content.getBytes("utf-8");
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密字符串
     * 
     * @param content
     * @param password
     * @return
     */
    public static byte[] decrypt(byte[] content, String sKey) {
        try {
            // 初始化 加密器
            Cipher cipher = initAESCipher(sKey, Cipher.DECRYPT_MODE);
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对文件进行AES加密
     * 
     * @param sourceFile
     * @param fileType
     * @param sKey
     * @return
     */
    public static File encryptFile(File sourceFile, File encrypfile, String sKey) {

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(sourceFile);

            outputStream = new FileOutputStream(encrypfile);
            Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
            // 以加密流写入文件
            CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
            byte[] cache = new byte[1024];
            int nRead = 0;
            while ((nRead = cipherInputStream.read(cache)) != -1) {
                outputStream.write(cache, 0, nRead);
                outputStream.flush();
            }
            cipherInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
        }
        return encrypfile;
    }
    
    public static File encryptFile(InputStream inputStream, File encrypfile, String sKey) {

        OutputStream outputStream = null;
        try {

            outputStream = new FileOutputStream(encrypfile);
            Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
            // 以加密流写入文件
            CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
            byte[] cache = new byte[1024];
            int nRead = 0;
            while ((nRead = cipherInputStream.read(cache)) != -1) {
                outputStream.write(cache, 0, nRead);
                outputStream.flush();
            }
            cipherInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
        }
        return encrypfile;
    }

    /**
     * AES方式解密文件
     * 
     * @param sourceFile  要解密的文件路径
     * @param decryptFile 解密后的文件路径
     * @param sKey
     * @return
     */
    public static File decryptFile(File sourceFile, File decryptFile, String sKey) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            Cipher cipher = initAESCipher(sKey, Cipher.DECRYPT_MODE);
            inputStream = new FileInputStream(sourceFile);
            outputStream = new FileOutputStream(decryptFile);
            CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = inputStream.read(buffer)) >= 0) {
                cipherOutputStream.write(buffer, 0, r);
            }
            cipherOutputStream.close();
        } catch (IOException e) {
            logger.info("IOException");
            logger.info(e.getMessage());
            logger.info(e.getLocalizedMessage());
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
        }
        return decryptFile;
    }
    
    public static OutputStream decryptFile(File sourceFile,ServletOutputStream outputStream, String sKey) {
        InputStream inputStream = null;
        try {
            Cipher cipher = initAESCipher(sKey, Cipher.DECRYPT_MODE);
            inputStream = new FileInputStream(sourceFile);
            CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = inputStream.read(buffer)) >= 0) {
                cipherOutputStream.write(buffer, 0, r);
            }
            cipherOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); // To change body of catch statement use
                                        // File | Settings | File Templates.
            }
        }
        return outputStream;
    }

    /**
     * 初始化 AES Cipher
     * 
     * @param sKey
     * @param cipherMode
     * @return
     */
    
    public static Cipher initAESCipher(String sKey, int cipherMode) {
        // 创建Key gen
        KeyGenerator keyGenerator = null;
        Cipher cipher = null;
        try {
            keyGenerator = KeyGenerator.getInstance( "AES" );
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
            secureRandom.setSeed(sKey.getBytes());
            
            keyGenerator.init(128, secureRandom);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] codeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(codeFormat, "AES");
            cipher = Cipher.getInstance("AES");
            cipher.init(cipherMode, key);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } catch (NoSuchPaddingException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        } catch (InvalidKeyException e) {
            e.printStackTrace(); // To change body of catch statement use File |
                                    // Settings | File Templates.
        }
        return cipher;
    }
    
    public static File encryptFile(String oldfilePath, String encrypfilePath) {
        File oldfile = new File(oldfilePath);// 未加密文件路径
        File encrypfile = new File(encrypfilePath);// 加密后的文件路径
        return encryptFile(oldfile, encrypfile, cKey);// 加密文件
    }
    
    public static File decryptFile(String encrypfilePath, String decrypfilePath) {
        File encrypfile = new File(encrypfilePath);// 加密后的文件路径
        File decrypfile = new File(decrypfilePath);// 解密后的文件路径
        return decryptFile(encrypfile, decrypfile, cKey);// 解密文件
    }

    public static void main(String[] args) throws Exception {
        File oldfile = new File("D://123.pdf");// 未加密文件路径
        File encrypfile = new File("D://123-e.pdf");// 加密后的文件路径
        File decrypfile = new File("D://123-d.pdf");// 解密后的文件路径
        encryptFile(oldfile, encrypfile, cKey);// 加密文件
        decryptFile(encrypfile, decrypfile, cKey);// 解密文件
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值