base64加密解密文件,解决前后端对接出现的转换失败问题

这篇博客的前提是我在本地进行文件的加密和解密都是没有问题的,但是当前后端对接的时候出现了我对前端base64加密之后的pdf问价的字符串进行机密没有问题,但是对doc或者docx类型的文件加密字符串进行解密时出现解密文件失败.原因是前端传过来的字符串有个别的字符经历了转义,但是最终还是解决了这个问题,下面就是本人写的工具类.


//获取文件的类型
String suffixName = filename.substring(filename.lastIndexOf("."));
//文件类型
String filetype = suffixName.replace(".", "");
//文件名,因为.是特殊字符需要使用\\
String name = filename.split("\\.")[0];
**下面就是对base64加密后的字符串进行解密的过程**
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.File;
import java.io.IOException;
import java.util.Date;
public class DecodeUtil {

    //新生成的文件存储在本地
    public String save (MultipartFile file,String filetype,String name) throws IOException {

        String filepath = "/tmp/"+name+"."+filetype;  //生成的新文件
        File destFile = new File(filepath);
        file.transferTo(destFile);
        return filepath;
    }
    //解密base64字符串生成文件
    public MultipartFile base64toMultipart (String base64,String filetype) {
        return this.base64File(base64,filetype);
    }

    public Base64File base64File (String base64,String filetype) {
        try {
            String[] baseStr = base64.split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStr[1]);

            for (int i = 0 ; i < b.length ; i++) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64File(b, baseStr[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

base64加密解密demo如下:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class BaseUtil {

    public static String fileToBase64(String filepath, String filename) throws IOException {
        String fileName = filepath + filename; // 源文件
        String strBase64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(fileName);
            // in.available()返回文件的字节长度
            byte[] bytes = new byte[in.available()];
            // 将文件中的内容读入到数组中
            in.read(bytes);
            // strBase64 = new BASE64Encoder().encode(bytes); // 将字节流数组转换为字符串
            strBase64 = encode(bytes); // 将字节流数组转换为字符串
        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }finally{
            if(in!=null)
                in.close();
        }
        return strBase64;
    }

    public static String fileToBase64(String filepathame) throws IOException {
        String fileName = filepathame; // 源文件
        String strBase64 = null;
        try {
            InputStream in = new FileInputStream(fileName);
            // in.available()返回文件的字节长度
            byte[] bytes = new byte[in.available()];
            // 将文件中的内容读入到数组中
            in.read(bytes);
            // strBase64 = new BASE64Encoder().encode(bytes); // 将字节流数组转换为字符串
            strBase64 = encode(bytes); // 将字节流数组转换为字符串
            in.close();
        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return strBase64;
    }

    public static String base64ToFile(String strBase64, String filetype,String name) throws IOException {
        String string = strBase64;
        long time = new Date().getTime();
        String filepath = "/tmp/"+name+"."+filetype;  //生成的新文件
       // String fileName = filepath + filename;//
        ByteArrayInputStream in = null;
        FileOutputStream out = null;
        try {
            // 解码,然后将字节转换为文件
//             byte[] bytes = new BASE64Decoder().decodeBuffer(string);
             byte[] bytes = decode(string.trim().replaceAll(" ", ""));
           // byte[] bytes = decode(string.trim().replaceAll(" ", ""));
            // 将字符串转换为byte数组
            in = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            out = new FileOutputStream(filepath);
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread); // 文件写操作
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }finally{
            if(out!=null)
                out.flush();
                out.close();
            if(in!=null)
                in.close();
        }
        return filepath;
    }

    /**
     * 编码
     *
     * @param bstr
     * @return String
     */
    public static String encode(byte[] bstr) {
        return new BASE64Encoder().encode(bstr);
    }

    /**
     * 解码
     *
     * @param str
     * @return string
     */
    public static byte[] decode(String str) {
        byte[] bt = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            bt = decoder.decodeBuffer(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bt;
    }


    public static void main(String[] args) {
        try {
            String base64code = fileToBase64("/Users/fish/Desktop/2.doc");
            //将文件流化
            System.out.println();
            //将流化文件重新生成文件
            String path = base64ToFile(base64code,"doc","test");
            System.out.println(path);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            System.out.println("error");
            e1.printStackTrace();
        }
    }
}

在工具类中需要的Base64File类:

import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class Base64File implements MultipartFile {

    private final byte[] content;

    private final String header;

    public Base64File(byte[] content, String header) {
        this.content = content;
        this.header = header.split(";")[0];
    }

    public byte[] getContent() {
        return content;
    }

    public String getHeader() {
        return header;
    }

    @Override
    public String getName() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        // TODO - implementation depends on your requirements
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return content == null || content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(content);
    }
}

猜你喜欢

转载自blog.csdn.net/ligh_sqh/article/details/81736142