SprintBoot项目中利用DES文件加密解密

1. maven依赖

<dependency>
     <groupId>bcprov</groupId>
     <artifactId>bcprov</artifactId>
     <version>1.0</version>
</dependency>

2. DES加密解密工具类

package com.eongb0.common.utils;

import org.apache.tomcat.jni.FileInfo;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org2.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;


public class DesECBUtils {

	public static void main(String[] args)  {
		try {
			//String result = new DesECBUtile().decryptFile("870/g8C1Qso=","d:\\313.txt","d:\\313-3.txt");
			String key = new DesECBUtils().getKey();
			
			System.out.println(key);
            MultipartFile desFile= new MockMultipartFile("12.doc",new FileInputStream(new File("d:\\12.doc")));
			 new DesECBUtils().encryptDesFile(key,desFile);
			
			 new DesECBUtils().decryptFile(key,"123m.doc","d:\\12m--1.doc");
			//System.out.println(new DesECBUtile().getKey());
			
			//String result = new DesECBUtile().decryptFile("aGViY2E=","d:\\encrypt-zyq","d:\\encrypt-zyq-1");
			//String result = new DesECBUtile().decryptFile("XEMaC5YnGG0=","d:\\322.txt","d:\\322-1.txt");

		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    public static String getKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        keyGenerator.init(56);
        SecretKey generateKey = keyGenerator.generateKey();
        byte[] encoded = generateKey.getEncoded();
        return new String(Base64.encode(encoded));
    }

    public static String decryptFile(String key, String encryptFile, String srcFile) throws Exception {
        byte[] key1 = Base64.decode(key);
        //byte[] key1 = key.getBytes();

        byte[] buf;

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        File dir = new File(srcFile);
        if (!dir.exists() && dir.isDirectory()) {
            dir.mkdirs();
        }
        if (dir.exists()) {
            dir.delete();
            dir.createNewFile();
        }

        final int readArraySizePerRead = 4096;
        file = new File(encryptFile);
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        if (file.exists()) {
            DataInputStream isr = new DataInputStream(new FileInputStream(
                    file));
            byte[] tempchars = new byte[readArraySizePerRead];
            int charsReadCount = 0;

            fos = new FileOutputStream(dir);
            bos = new BufferedOutputStream(fos);

            SecureRandom sr = new SecureRandom();

            DESKeySpec dks = new DESKeySpec(key1);

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

            //return cipher.doFinal(data);
            int tt = 0, i = 0;
            byte[] bt;
            while ((charsReadCount = isr.read(tempchars)) != -1) {

                for (i = 0; i < charsReadCount; i++) {
                    bytes.add(tempchars[i]);
                }
                buf = toPrimitives(bytes.toArray(new Byte[0]));
                bytes.removeAll(bytes);
                bt = cipher.update(buf);
                if (bt.length > 0) {
                    bos.write(bt, tt, bt.length);
                }
            }
            bt = cipher.doFinal(new byte[0]);
            bos.write(bt, 0, bt.length);
        }
        if (bos != null) {
            bos.close();
        }
        if (fos != null) {
            fos.close();
        }

        return "1";
    }

    public static String decryptFile(String key, String encryptFile) throws Exception {
        byte[] key1 = Base64.decode(key);
        //byte[] key1 = key.getBytes();

        byte[] buf;
        StringBuffer bf = new StringBuffer();
        File file = null;

        final int readArraySizePerRead = 4096;
        file = new File(encryptFile);
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        if (file.exists()) {
            DataInputStream isr = new DataInputStream(new FileInputStream(
                    file));
            byte[] tempchars = new byte[readArraySizePerRead];
            int charsReadCount = 0;

            SecureRandom sr = new SecureRandom();

            DESKeySpec dks = new DESKeySpec(key1);

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

            //return cipher.doFinal(data);
            int tt = 0, i = 0;
            byte[] bt;
            while ((charsReadCount = isr.read(tempchars)) != -1) {

                for (i = 0; i < charsReadCount; i++) {
                    bytes.add(tempchars[i]);
                }
                buf = toPrimitives(bytes.toArray(new Byte[0]));
                bytes.removeAll(bytes);
                bt = cipher.update(buf);
            }
            bt = cipher.doFinal(new byte[0]);
            bf.append(bt);
        }

        return bf.toString();
    }

    public static String encryptFile(String key, String srcFile, String encryptFile) throws Exception {
        byte[] key1 = Base64.decode(key);

        byte[] buf;

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        File dir = new File(encryptFile);
        if (!dir.exists() && dir.isDirectory()) {
            dir.mkdirs();
        }
        if (dir.exists()) {
            dir.delete();
            dir.createNewFile();
        }

        final int readArraySizePerRead = 4096;
        file = new File(srcFile);
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        if (file.exists()) {
            DataInputStream isr = new DataInputStream(new FileInputStream(file));
            byte[] tempchars = new byte[readArraySizePerRead];
            int charsReadCount = 0;

            fos = new FileOutputStream(dir);
            bos = new BufferedOutputStream(fos);

            SecureRandom sr = new SecureRandom();

            DESKeySpec dks = new DESKeySpec(key1);

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

            int tt = 0, i = 0;
            byte[] bt;
            while ((charsReadCount = isr.read(tempchars)) != -1) {

                for (i = 0; i < charsReadCount; i++) {
                    bytes.add(tempchars[i]);
                }
                buf = toPrimitives(bytes.toArray(new Byte[0]));
                bytes.removeAll(bytes);
                bt = cipher.update(buf);
                if (bt.length > 0) {
                    bos.write(bt, tt, bt.length);
                }
            }
            bt = cipher.doFinal(new byte[0]);
            bos.write(bt, 0, bt.length);
        }
        if (bos != null) {
            bos.close();
        }
        if (fos != null) {
            fos.close();
        }

        return "1";
    }



    static byte[] toPrimitives(Byte[] oBytes) {
        byte[] bytes = new byte[oBytes.length];

        for (int i = 0; i < oBytes.length; i++) {
            bytes[i] = oBytes[i];
        }
        return bytes;
    }
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static byte[] encryptbyteFile(String key, MultipartFile file) throws Exception {
        byte[] key1 = Base64.decode(key);
        byte[] buf;
        String encryptFile="d:\\123m.doc";
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;

        final int readArraySizePerRead = 4096;
        // File files =multipartFileToFile(file) ;
        ArrayList<Byte> bytes = new ArrayList<Byte>();
            DataInputStream isr = new DataInputStream(file.getInputStream());
            byte[] tempchars = new byte[readArraySizePerRead];
            int charsReadCount = 0;

            fos = new FileOutputStream("");
            bos = new BufferedOutputStream(fos);
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(key1);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

            int tt = 0, i = 0;
            byte[] bt;
            while ((charsReadCount = isr.read(tempchars)) != -1) {

                for (i = 0; i < charsReadCount; i++) {
                    bytes.add(tempchars[i]);
                }
                buf = toPrimitives(bytes.toArray(new Byte[0]));
                bytes.removeAll(bytes);
                bt = cipher.update(buf);
                if (bt.length > 0) {
                    bos.write(bt, tt, bt.length);
                }
            }
            bt = cipher.doFinal(new byte[0]);

            InputStream inputStream = new ByteArrayInputStream(bt);
            bos.write(bt, 0, bt.length);
        if (bos != null) {
            bos.close();
        }
        if (fos != null) {
            fos.close();
        }

        return bt;


    }
    public static MultipartFile encryptDesFile(String key, MultipartFile file) throws Exception {
        byte[] key1 = Base64.decode(key);
        byte[] buf;
        String encryptFile=GTime.getTime(GTime.YYYYMMDDhhmmssxxx)+file.getOriginalFilename();
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        final int readArraySizePerRead = 4096;
      // File files =multipartFileToFile(file) ;
        ArrayList<Byte> bytes = new ArrayList<Byte>();

            DataInputStream isr = new DataInputStream(file.getInputStream());
            byte[] tempchars = new byte[readArraySizePerRead];
            int charsReadCount = 0;
            fos = new FileOutputStream(encryptFile);
            bos = new BufferedOutputStream(fos);
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(key1);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

            int tt = 0, i = 0;
            byte[] bt;
            while ((charsReadCount = isr.read(tempchars)) != -1) {

                for (i = 0; i < charsReadCount; i++) {
                    bytes.add(tempchars[i]);
                }
                buf = toPrimitives(bytes.toArray(new Byte[0]));
                bytes.removeAll(bytes);
                bt = cipher.update(buf);
                if (bt.length > 0) {
                    bos.write(bt, tt, bt.length);
                }
            }
            bt = cipher.doFinal(new byte[0]);

            InputStream inputStream = new ByteArrayInputStream(bt);
            bos.write(bt, 0, bt.length);
         if (bos != null) {
            bos.close();
        }
        if (fos != null) {
            fos.close();
        }
        File jmhfile=new File(encryptFile);
        MultipartFile desFile= new MockMultipartFile(file.getName(),file.getOriginalFilename(),file.getContentType(),new FileInputStream(jmhfile));
        jmhfile.delete();
        return desFile;
    }

    public static void decryptFileBybytes(String key, byte[] jmbytes, String filename, HttpServletResponse response)throws Exception {
        byte[] key1 = Base64.decode(key);
        //byte[] key1 = key.getBytes();
        byte[] buf;
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        File dir = new File(filename);
        final int readArraySizePerRead = 4096;
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
        bos = new BufferedOutputStream(response.getOutputStream());
            InputStream inputStream = new ByteArrayInputStream(jmbytes);
            DataInputStream isr = new DataInputStream(inputStream);
            byte[] tempchars = new byte[readArraySizePerRead];
            int charsReadCount = 0;
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(key1);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
            //return cipher.doFinal(data);
            int tt = 0, i = 0;
            byte[] bt;
            while ((charsReadCount = isr.read(tempchars)) != -1) {
                for (i = 0; i < charsReadCount; i++) {
                    bytes.add(tempchars[i]);
                }
                buf = toPrimitives(bytes.toArray(new Byte[0]));
                bytes.removeAll(bytes);
                bt = cipher.update(buf);
                if (bt.length > 0) {
                    bos.write(bt, tt, bt.length);
                }
            }
            bt = cipher.doFinal(new byte[0]);
        bos.write(bt, 0, bt.length);
        bos.flush();
        bos.close();
      //  return bt;
    }
}

3. 文件加密解密接口

/**
     * 文件上传
     * 根据fileType选择上传方式
     *
     * @param file
     * @return
     * @throws Exception
     */
@PostMapping("/files-anon")
public FileInfo upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
        String key = ""; //对称密钥
        //生成对接加密的密钥
        try {
            key = DesECBUtils.getKey();
        } catch (NoSuchAlgorithmException e) {
            System.out.println("对称加密密钥生成失败:异常信息" + e.getMessage());
        }
        MultipartFile desFile = DesECBUtils.encryptDesFile(key,file);
        return fileService.upload(key,desFile);
    }


@ApiOperation("文件解密")
@GetMapping("/files-decrypt")
public void decryptFile(@RequestParam Map<String,Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileUrl = MapUtils.getString(params,"fileUrl");
        String fileId = MapUtils.getString(params,"fileId");
        FileInfo fileInfo = fileService.getById(fileId);
        byte[] jmbytes = fileService.download(fileId);
        String key = fileInfo.getKey();
        DesECBUtils.decryptFileBybytes(key,jmbytes,fileInfo.getName(),response);
}

 

posted @ 2020-03-21 16:13  petrolero  阅读(1586)  评论(0编辑  收藏  举报