zoukankan      html  css  js  c++  java
  • AES加解密文件流

    package com.yang.ftpdemo.crypt;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.util.Random;
    import java.util.UUID;
    
    @Slf4j
    @RestController
    @RequestMapping("/file")
    public class FileController {
    
        /**
         * 加密接口
         *
         * @param file 文件本体
         * @return
         */
        @PostMapping("/encrypt")
        public void encrypt(@RequestParam("file") MultipartFile file) throws IOException {
            if (file.isEmpty()) {
                log.error("【保存失败!文件出错,file={}】", file);
            }
            // 文件名加上文件后缀名
            String originalName = file.getOriginalFilename();
            String suffixName = originalName.substring(originalName.lastIndexOf("."));
            String filename = UUID.randomUUID() + String.valueOf(new Random().nextInt(1000)) + suffixName;
            encrypt(file.getInputStream(), new FileOutputStream("D:\22222222.exe"), initAESCipher("123", 1));
        }
    
        /**
         * 加密静态方法
         *
         * @param inputStream
         * @param outputStream
         * @param cipher
         */
        public static void encrypt(InputStream inputStream, OutputStream outputStream, Cipher cipher) {
            try {
                // 创建加密流
                CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
                int isread = 0;
                byte[] cache = new byte[1024];
                // 加密流写入文件
                while ((isread = cipherInputStream.read(cache, 0, cache.length)) != -1) {
                    outputStream.write(cache, 0, isread);
                }
                cipherInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.flush();
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 解密接口
         *
         * @param response
         * @param file
         * @throws IOException
         */
        @PostMapping("/decrypt")
        public void decrypt(HttpServletResponse response, @RequestParam("file") MultipartFile file) throws IOException {
            response.setHeader("content-disposition", "attachment;filename=1333");
            decrypt(file.getInputStream(), response.getOutputStream(), initAESCipher("123", 2));
        }
    
        /**
         * 解密静态方法
         *
         * @param inputStream
         * @param outputStream
         * @param cipher
         */
        public static void decrypt(InputStream inputStream, OutputStream outputStream, Cipher cipher) {
            try {
                // 创建解密流
                CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
                int isread = 0;
                byte[] cache = new byte[1024];
                while ((isread = inputStream.read(cache, 0, cache.length)) != -1) {
                    cipherOutputStream.write(cache, 0, isread);
                }
                cipherOutputStream.flush();
                cipherOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.flush();
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * Cipher初始化静态方法
         *
         * @param sKey
         * @param cipherMode
         * @return
         */
        public static Cipher initAESCipher(String sKey, int cipherMode) {
            Cipher cipher = null;
            KeyGenerator generator = null;
            try {
                generator = KeyGenerator.getInstance("AES");
                generator.init(128, new SecureRandom(sKey.getBytes()));
    
                SecretKey secretKey = generator.generateKey();
                byte[] codeFormat = secretKey.getEncoded();
    
                cipher = Cipher.getInstance("AES");
                SecretKeySpec keySpec = new SecretKeySpec(codeFormat, "AES");
    
                cipher.init(cipherMode, keySpec);
            } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
                e.printStackTrace();
            }
            return cipher;
        }
    }
    
    
  • 相关阅读:
    SQL注入与防范
    JDCP连接池连接数据库报错:java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
    数据库连接池(基于MySQL数据库)
    使用JDBC连接MySQL数据库的一个基本案例
    快速排序的java实现
    在C++的函数中如何指定一个数组,使得这个数组的大小由函数的输入值来决定
    WORD2010如何把全角字母和数字批量转换成半角
    地图安卓
    浅谈java异常[Exception]
    Adapter的getView
  • 原文地址:https://www.cnblogs.com/JaxYoun/p/13156944.html
Copyright © 2011-2022 走看看