import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Base64;
/**
* base64实现单个文件的加密解密
*
* @author syl
*/
@Slf4j
public class PictureEncryption {
private static InputStream in=null;
private static OutputStream out=null;
/**
*
* @param encode 要解密的
* @param decodePath 解密路径
* @throws IOException
*/
private static void decodeFile(byte[] encode,String decodePath) throws IOException {
//图片的解密
log.info("开始解密.....");
byte[] decode = Base64.getDecoder().decode(encode);
File deFile = new File(decodePath);
if (!deFile.exists()){
deFile.createNewFile();
}
out=new BufferedOutputStream(new FileOutputStream(deFile));
out.write(decode);
log.info("解密完成.....");
}
/**
*
* @param srcPath 要加密的文件
* @param encodePath 加密之后的文件 xxx.txt
* @return
* @throws IOException
*/
private static byte[] fileEncode(String srcPath,String encodePath) throws IOException {
log.info("开始加密.....");
File file=new File(srcPath);
in=new BufferedInputStream(new FileInputStream(file));
int available = in.available();
byte [] bytes=new byte[available];
in.read(bytes);
in.close();
byte[] encode = Base64.getEncoder().encode(bytes);
File enFile = new File(encodePath);
if (!enFile.exists()){
enFile.createNewFile();
}
out=new BufferedOutputStream(new FileOutputStream(enFile));
out.write(encode);
log.info("加密完成.....");
return encode;
}
public static void main(String[] args) {
try {
//图片的加密
String srcPath = "H:\\pic\\地址.xlsx";
String encodePath = "H:\\pic\\加密2.txt";
byte[] encode = fileEncode(srcPath,encodePath);
String decodePath="H:\\pic\\地址1.xlsx";
decodeFile(encode,decodePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过base64实现单个文件的加密解密
于 2021-02-25 17:11:22 首次发布