栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

AES128文件内容快速加密

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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";

    
    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;
    }

    
    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;
    }

    
    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;
    }

    
    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;
    }

    
    
    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);// 解密文件
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1032572.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号