当前位置: 首页 > news >正文

加解密算法+压缩工具

sha256 工具类

package com.fanghui.vota.packages.util;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;/*** sha256 工具类** @author fanghui on 2017/3/30.*/
public class Sha256Util {private static Logger logger = LoggerFactory.getLogger(Sha256Util.class);private static final int BUFF_SIZE = 1024 * 1024;public static String fileSha256(File file) {FileInputStream in = null;byte[] buffer = new byte[1024];int len;MessageDigest messageDigest = null;try {messageDigest = MessageDigest.getInstance("SHA-256");in = new FileInputStream(file);while ((len = in.read(buffer, 0, 1024)) != -1) {messageDigest.update(buffer, 0, len);}} catch (NoSuchAlgorithmException e) {logger.error("error:" + e);return null;} catch (FileNotFoundException e) {logger.error("error:" + e);return null;} catch (IOException e) {logger.error("error:" + e);return null;} finally {if (in != null) {try {in.close();} catch (IOException e) {logger.error("error:" + e);}}}BigInteger bigInt = new BigInteger(1, messageDigest.digest());return bigInt.toString(16);}/*** TODO 客户端的加密算法** @param deltaFilePath* @return* @author sheng*/public static String getClientSha256(String deltaFilePath) {FileInputStream fis = null;StringBuffer buf = new StringBuffer();try {MessageDigest md = MessageDigest.getInstance("SHA-256");fis = new FileInputStream(deltaFilePath);byte[] buffer = new byte[BUFF_SIZE];int length = -1;if (fis == null || md == null) {return null;}while ((length = fis.read(buffer)) != -1) {md.update(buffer, 0, length);}byte[] bytes = md.digest();if (bytes == null) {return null;}for (int i = 0; i < bytes.length; i++) {String md5s = Integer.toHexString(bytes[i] & 0xff);if (md5s == null || buf == null) {return null;}if (md5s.length() == 1) {buf.append("0");}buf.append(md5s);}return buf.toString();} catch (Exception ex) {logger.error("计算文件hash失败!异常信息:",ex);throw new RuntimeException("calculate file sha256 exception.");} finally {try {if (fis != null) {fis.close();}} catch (IOException ex) {logger.error("计算文件hash失败!异常信息:",ex);}}}}

shell脚本执行类

package com.fanghui.vota.packages.util;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;/*** TODO shell脚本执行类** @author fanghui*/
public class ShellCommodUtil {private static Logger logger = LoggerFactory.getLogger(ShellCommodUtil.class);/*** 运行shell脚本** @param shell* @return* @throws Exception*/public static boolean runShellBoolean(String shell) throws Exception {logger.info("begin run shell:{}", shell);String[] cmd = {"/bin/sh", "-c", shell};//执行命令Process process = Runtime.getRuntime().exec(cmd);InputStream childIn = process.getInputStream();BufferedReader in = new BufferedReader(new InputStreamReader(childIn));String line = "";logger.info("Shell process in.readLine :>>>>>>>>>>>>>>>>:{}" , in.readLine());while ((line = in.readLine()) != null) {logger.info("runShell: {}" ,line);}BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));while ((line = stderrReader.readLine()) != null) {logger.info("runShell: {}" , line);}int exitValue = process.waitFor();//脚本正确执行返回值为0logger.info("***执行结果***:{}" , exitValue);childIn.close();in.close();stderrReader.close();process.destroy();return true;}
}

文件的AES加解密

package com.fanghui.vota.packages.util;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.GeneralSecurityException;/*** 文件的AES加解密** @Author: fh* @Date: 2019-05-24 18:46*/
public class AesFileUtil {private static Logger logger = LoggerFactory.getLogger(AesFileUtil.class);/*** 分段加密大小*/final static int SEGSIZE = 1024 * 1024;/*** AES加密算法*/private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";/*** AES分段文件加密** @param file* @param encryptedFile* @param password* @return*/public static boolean fileSegAesEncrypt(File file, String encryptedFile, String password) {if (file == null || !file.exists()) {logger.error("fileSegAesEncrypt error,encrypt file is not exit");return false;}FileInputStream is = null;FileOutputStream output = null;try {//输入文件is = new FileInputStream(file);// 输出到文件output = new FileOutputStream(new File(encryptedFile));byte[] buf = new byte[SEGSIZE];int numBytesRead = 0;while ((numBytesRead = is.read(buf)) != -1) {if (numBytesRead != SEGSIZE) {byte[] data = new byte[numBytesRead];System.arraycopy(buf, 0, data, 0, numBytesRead);byte[] encrypt = aesEncrypt(data, password);output.write(encrypt, 0, encrypt.length);continue;}byte[] encrypt = aesEncrypt(buf, password);output.write(encrypt, 0, encrypt.length);}} catch (IOException | GeneralSecurityException e) {logger.error("error:" + e);logger.error("fileSegAesEncrypt error:" + e.getMessage());return false;} finally {closeStream(is, output);}return true;}private static void closeStream(FileInputStream is, FileOutputStream output) {if (is != null) {try {is.close();} catch (IOException e) {logger.error("error:" + e);}}if (output != null) {try {output.close();} catch (IOException e) {logger.error("error:" + e);}}}/*** AES文件加密** @param file* @param encryptedFile* @param password* @return*/public static boolean fileAesEncrypt(File file, String encryptedFile, String password) {if (file == null || !file.exists()) {logger.error("fileAesEncrypt error,encrypt file is not exit");return false;}FileInputStream is = null;FileOutputStream os = null;try {byte[] source = new byte[(int) file.length()];is = new FileInputStream(file);is.read(source, 0, (int) file.length());// 加密byte[] enc;enc = aesEncrypt(source, password);// 输出到文件os = new FileOutputStream(new File(encryptedFile));os.write(enc, 0, enc.length);} catch (IOException | GeneralSecurityException e) {logger.error("fileAesEncrypt error:" + e);return false;} finally {closeStream(is, os);}return true;}private static byte[] aesEncrypt(byte[] source, String password) throws GeneralSecurityException, UnsupportedEncodingException {byte[] strDefaultKey = password.getBytes("UTF-8");// 处理密钥SecretKeySpec key = new SecretKeySpec(strDefaultKey, "AES");// 加密Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, key);return cipher.doFinal(source);}/*** 对AES加密后的文件进行解密** @param encryptedFile* @param decryptedFile* @param password* @return*/public static boolean fileAesDecrypt(File encryptedFile, String decryptedFile, String password) {if (encryptedFile == null || !encryptedFile.exists()) {logger.error("fileAesDecrypt error,encryptedFile is not exit");return false;}FileInputStream is = null;FileOutputStream os = null;try {byte[] data = new byte[(int) encryptedFile.length()];is = new FileInputStream(encryptedFile);is.read(data, 0, (int) encryptedFile.length());// 加密byte[] dec;dec = aesDecrypt(data, password);// 输出到文件os = new FileOutputStream(new File(decryptedFile));os.write(dec, 0, dec.length);} catch (IOException | GeneralSecurityException e) {logger.error("fileAesDecrypt error:" + e);return false;} finally {closeStream(is, os);}return true;}/*** 对AES分段加密好的文件进行解密** @param encryptedFile 待解密文件* @param decryptedFile 解密后输出文件* @param password 密钥*/public static boolean fileSegAesDecrypt(File encryptedFile, String decryptedFile, String password) {if (encryptedFile == null || !encryptedFile.exists()) {logger.error("fileSegAesDecrypt error,encryptedFile is not exit");return false;}FileInputStream is = null;FileOutputStream output = null;try {//输入文件is = new FileInputStream(encryptedFile);// 输出到文件output = new FileOutputStream(new File(decryptedFile));byte[] buf = new byte[SEGSIZE + 16];int numBytesRead = 0;while ((numBytesRead = is.read(buf)) != -1) {if (numBytesRead != SEGSIZE) {byte[] data = new byte[numBytesRead];System.arraycopy(buf, 0, data, 0, numBytesRead);byte[] encrypt = aesDecrypt(data, password);output.write(encrypt, 0, encrypt.length);continue;}byte[] encrypt = aesDecrypt(buf, password);output.write(encrypt, 0, encrypt.length);}} catch (IOException | GeneralSecurityException e) {logger.error("fileSegAesDecrypt error:{}",e);return false;} finally {closeStream(is, output);}return true;}private static byte[] aesDecrypt(byte[] data, String password) throws GeneralSecurityException, UnsupportedEncodingException {// 处理密钥byte[] strDefaultKey = password.getBytes("UTF-8");SecretKeySpec key = new SecretKeySpec(strDefaultKey, "AES");// 解密Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, key);return cipher.doFinal(data);}public static void main(String[] args) {
//        File fileOrg = new File("D:\\差分工具包\\orgFile");
//        String password = "f70e300942ea540ed365fe0eb05b5585";
//        String encPath = "D:\\差分工具包\\java_enc_File";
//        fileSegAesEncrypt(fileOrg, encPath, password);
//
//        String deEncPath = "D:\\差分工具包\\de_java_enc_File";
//        fileSegAesDecrypt(new File(encPath), deEncPath, password);}
}

压缩工具类

package com.fanghui.vota.packages.util;import com.alibaba.cloud.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;public class ZipUtil {private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);private static final int BUFF_SIZE = 4 * 1024;/*** 解压** @param zipFilePath 压缩文件* @param unzipPath   解压路径* @return return true if success*/public static String unzip(String zipFilePath, String unzipPath) throws IOException {File zFile = new File(zipFilePath);// 如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径String fileName = zFile.getName();if (StringUtils.isNotEmpty(fileName)) {fileName = fileName.substring(0, fileName.lastIndexOf("."));}unzipPath = unzipPath + fileName + "/";logger.info("**解压准备**" + unzipPath);ZipFile zipFile = null;try {zipFile = new ZipFile(zipFilePath, Charset.forName("GBK"));Enumeration emu = zipFile.entries();int i = 0;while (emu.hasMoreElements()) {ZipEntry entry = (ZipEntry) emu.nextElement();if (entry.isDirectory()) {new File(unzipPath + entry.getName()).mkdirs();continue;}BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));File file = new File(unzipPath + entry.getName());File parent = file.getParentFile();if (parent != null && (!parent.exists())) {parent.mkdirs();}FileOutputStream fos = null;BufferedOutputStream bos = null;try {fos = new FileOutputStream(file);bos = new BufferedOutputStream(fos);int count;byte[] data = new byte[BUFF_SIZE];while ((count = bis.read(data, 0, BUFF_SIZE)) != -1) {bos.write(data, 0, count);}bos.flush();} catch (IOException e) {e.printStackTrace();} finally {if (Objects.nonNull(bos)) {bos.close();}if (Objects.nonNull(fos)) {fos.close();}}}logger.info("**解压完成**: {}", unzipPath);return unzipPath;} catch (Exception e) {logger.info(String.valueOf(e));logger.info("ZipUtil unzip error! zip file:{},unzip to path:{}", zipFilePath ,unzipPath);return "";} finally {if (zipFile != null) {zipFile.close();}}}
}
http://www.lryc.cn/news/107740.html

相关文章:

  • FeignClient接口的几种方式总结
  • springBoot多数据源使用tdengine(3.0.7.1)+MySQL+mybatisPlus+druid连接池
  • 剑指Offer 05.替换空格
  • ChatGPT的功能与特点
  • Vue2.0基础
  • rust 如何定义[u8]数组?
  • 关于Hive的使用技巧
  • 【C++】BSTree 模拟笔记
  • 5分钟快手入门laravel邮件通知
  • iOS——Block two
  • Ubuntu出现内部错误解决办法
  • 2023年中职组“网络安全”赛项吉安市竞赛任务书
  • ELK日志分析系统介绍及搭建(超详细)
  • docker 资源限制
  • HCIP 交换综合实验--企业三层架构
  • 微服务的基础使用
  • opencv-29 Otsu 处理(图像分割)
  • 网络中通过IP地址查找位置
  • MyBatis的动态SQL语句
  • 交互式AI技术与模型部署:bert-base-chinese模型交互式问答界面设置
  • Edge浏览器安装vue devtools
  • zookeeper基础
  • 【C++】类与对象(2)
  • 数据结构——绪论
  • Docker Dockerfile 语法与指令
  • 【LeetCode每日一题】——566.重塑矩阵
  • Manim(一款强大的数学可视化动画引擎)学习历程
  • powershell脚本写一个托盘图标
  • 前端Vue入门-day08-vant组件库
  • 华为OD机考--【磁盘容量排序】