AES文件加解密工具类 AESUtils

AES文件加解密工具类


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;

/**
 * @Description: AES加密工具类
 * @Author: 云诺
 * @Date: 2020/12/31 14:18
 * @return: null
 */
@Slf4j
public class AESUtil {

    /**
     * AES加密密钥 需要保证与单机版本校验程序中的key值一致
     */
    public static final String KEY = "password";

    /**
     * AES加解密编码格式
     */
    private static final String ENCODE = "UTF-8";

    /**
     * init AES Cipher
     *
     * @param passsword
     * @param cipherMode
     * @return
     */
    private static Cipher initAESCipher(String passsword, int cipherMode) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        Cipher cipher = null;
        SecretKey key = getKey(passsword);
        cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(cipherMode, key);
        return cipher;
    }

    private static SecretKey getKey(String password) {
        int keyLength = 256;
        byte[] keyBytes = new byte[keyLength / 8];
        SecretKeySpec key = null;
        try {
            Arrays.fill(keyBytes, (byte) 0x0);
            Security.addProvider(new BouncyCastleProvider());
            byte[] passwordBytes = password.getBytes(ENCODE);
            int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
            System.arraycopy(passwordBytes, 0, keyBytes, 0, length);

            key = new SecretKeySpec(keyBytes, "AES");
        } catch (UnsupportedEncodingException e) {
            log.error("AES获取key失败!");
            e.printStackTrace();
        }
        return key;
    }

    /**
     * @param jsonString: 需要被加密的字符串
     * @param skey:       密钥  取系统配置的秘钥 ,默认为 null
     * @Description: AES 字符串 加密
     * @Author: jdzt.lln
     * @Date: 2021/1/8 16:06
     * @return: java.lang.String
     */
    public static String encryptString(String jsonString, String skey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        skey = KEY;
        Cipher cipher = initAESCipher(skey, Cipher.ENCRYPT_MODE);
        try {
            byte[] byteContent = jsonString.getBytes(ENCODE);
            byte[] result = cipher.doFinal(byteContent);
            String res = Base64.encodeBase64String(result);
            return res;
        } catch (UnsupportedEncodingException e) {
            log.error("AES-encryptString()编码异常!");
            e.printStackTrace();
        } catch (BadPaddingException e) {
            log.error("AES-encryptString()错误的填充异常!");
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            log.error("AES-encryptString()非法块大小异常!");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param encryptPath 被加密文件 文件绝对路径
     * @param decryptPath 加密后文件 文件绝对路径
     * @param sKey        密钥  取系统配置的秘钥 ,默认为 null
     * @return 加密成功  true  加密失败 false
     * @Description: AES 文件加密
     */
    public static boolean encryptFile(String encryptPath, String decryptPath, String sKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        sKey = KEY;
        long start = System.currentTimeMillis();
        File encryptFile = null;
        File decryptfile = null;
        CipherOutputStream cipherOutputStream = null;
        BufferedInputStream bufferedInputStream = null;

        try {
            encryptFile = new File(encryptPath);
            if (!encryptFile.exists()) {
                throw new NullPointerException("Encrypt file is empty");
            }
            decryptfile = new File(decryptPath);
            if (decryptfile.exists()) {
                decryptfile.delete();
            }
            decryptfile.createNewFile();

            Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
            cipherOutputStream = new CipherOutputStream(new FileOutputStream(decryptfile), cipher);
            bufferedInputStream = new BufferedInputStream(new FileInputStream(encryptFile));

            byte[] buffer = new byte[1024 * 1024 * 5];
            int bufferLength;

            while ((bufferLength = bufferedInputStream.read(buffer)) != -1) {
                cipherOutputStream.write(buffer, 0, bufferLength);
            }
            bufferedInputStream.close();
            cipherOutputStream.close();
        } catch (IOException e) {
            delFile(decryptfile.getAbsolutePath());
            log.error("AES加密IO异常");
            return false;
        }
        long endTime = System.currentTimeMillis();
        log.info("加密时间:" + (endTime - start) + "ms");
        return true;
    }


    public static String decryptString(String decryptString, String mkey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        mkey = KEY;
        Cipher cipher = initAESCipher(mkey, Cipher.DECRYPT_MODE);
        byte[] result = cipher.doFinal(Base64.decodeBase64(decryptString));
        String res = new String(result, ENCODE);
        return res;
    }

    /**
     * @param encryptFile 需解密文件
     * @param mKey        密钥  取系统配置的秘钥 ,默认为 null
     * @return 解密成功后的内容字符串
     * @Description: AES 文件解密为字符串
     */
    public static String decryptFile2String(File encryptFile, String mKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        mKey = KEY;
        long start = System.currentTimeMillis();
        BufferedOutputStream outputStream = null;
        CipherInputStream inputStream = null;
        String res = "";
        try {
            if (!encryptFile.exists()) {
                log.error("找不到该文件!");
                throw new NullPointerException("Decrypt file is empty");
            }

            Cipher cipher = initAESCipher(mKey, Cipher.DECRYPT_MODE);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            inputStream = new CipherInputStream(new FileInputStream(encryptFile), cipher);

            int bufferLength;
            byte[] buffer = new byte[1024 * 1024 * 5];
            while ((bufferLength = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, bufferLength);
            }
            res = new String(baos.toByteArray());
            inputStream.close();
            baos.close();
        } catch (IOException e) {
            log.error("文件解密失败" + e + e.getMessage());
            return res;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("解密时间:" + (endTime - start) + "ms");
        return res;
    }

    /**
     * @param encryptPath 需解密文件 文件绝对路径
     * @param decryptPath 解密后文件 文件绝对路径
     * @param mKey        密钥  取系统配置的秘钥 ,默认为 null
     * @return 解密成功  true  解密失败 false
     * @Description: AES 已加密文件解密为正常文件
     */

    public static boolean decryptFile(String encryptPath, String decryptPath, String mKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        mKey = KEY;
        long start = System.currentTimeMillis();
        File encryptFile = null;
        File decryptFile = null;
        BufferedOutputStream outputStream = null;
        CipherInputStream inputStream = null;
        try {
            encryptFile = new File(encryptPath);
            if (!encryptFile.exists()) {
                throw new NullPointerException("Decrypt file is empty");
            }
            decryptFile = new File(decryptPath);
            if (decryptFile.exists()) {
                decryptFile.delete();
            }
            decryptFile.createNewFile();

            Cipher cipher = initAESCipher(mKey, Cipher.DECRYPT_MODE);

            outputStream = new BufferedOutputStream(new FileOutputStream(decryptFile));
            inputStream = new CipherInputStream(new FileInputStream(encryptFile), cipher);

            int bufferLength;
            byte[] buffer = new byte[1024 * 1024 * 5];

            while ((bufferLength = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bufferLength);
            }
            inputStream.close();
            outputStream.close();
//            delFile(encryptPath);
        } catch (IOException e) {
            delFile(decryptFile.getAbsolutePath());
            log.error("文件解密失败" + e + e.getMessage());
            return false;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("解密时间:" + (endTime - start) + "ms");
        return true;
    }


    /**
     * 删除文件
     *
     * @param pathFile 需要删除的文件绝对路径
     * @return
     */
    public static boolean delFile(String pathFile) {
        boolean flag = false;
        if (pathFile == null && pathFile.length() <= 0) {
            throw new NullPointerException("文件不能为空");
        } else {
            File file = new File(pathFile);
            // 路径为文件且不为空则进行删除
            if (file.isFile() && file.exists()) {
                file.delete();
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 以文件流方式进行解密
     *
     * @param inputStream
     * @param key         java.io.InputStream
     * @param inputStream
     * @param key
     * @return
     * @Title: encryptFile
     * @Description: 以文件流方式进行解密
     * @author 云诺
     */
    public static InputStream encryptFile(InputStream inputStream, String key) throws IOException {
        key = KEY;
        long start = System.currentTimeMillis();
        try {
            Cipher cipher = null;
            try {
                cipher = initAESCipher(key, Cipher.DECRYPT_MODE);
                inputStream = new CipherInputStream(inputStream, cipher);
                long endTime = System.currentTimeMillis();
                System.out.println("解密时间:" + (endTime - start) + "ms");
                return inputStream;
            } catch (NoSuchPaddingException e) {
                log.error("文件解密失败" + e + e.getMessage());
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                log.error("文件解密失败" + e + e.getMessage());
                e.printStackTrace();
            }
        } catch (InvalidKeyException e) {
            log.error("文件解密失败" + e + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小诺大人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值