加解密算法+压缩工具

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();
        //脚本正确执行返回值为0
        logger.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();
            }
        }
    }
}
相关推荐
闲人编程4 个月前
Python 实现 SHA-1 数字摘要签名算法
开发语言·python·算法·密码学·加解密·数字签名·sha
爱桥代码的程序媛5 个月前
鸿蒙系统开发【加解密】安全
安全·华为·harmonyos·鸿蒙·openharmony·加解密·鸿蒙开发
青石路5 个月前
异构数据源数据同步 → 从源码分析 DataX 敏感信息的加解密
datax·加解密
小程序照片合成5 个月前
vue引入sm-crypto通过sm4对文件进行加解密,用户输入密码
前端·javascript·vue·加解密·sm-crypto·sm4
大碍桃花开5 个月前
axios使用sm2加密数据后请求参数多了双引号解决方法
axios·加解密·前后端参数交互
Android技术栈5 个月前
鸿蒙开发:Universal Keystore Kit(密钥管理服务)【加解密(ArkTS)】
程序员·移动开发·harmonyos·arkts·openharmony·加解密·鸿蒙开发
我要出家当道士6 个月前
OpenSSL的一些使用案例
linux·c·加解密·openssl·通讯加密
吕氏春秋i1 年前
android 网络拦截器统一处理请求参数和返回值加解密实现
android·网络·aes·拦截器·加解密·rsa
gsls2008081 年前
java使用bouncycastle加解密
java·des·加解密·rsa