加解密算法+压缩工具

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();
            }
        }
    }
}
相关推荐
Monkey-旭18 天前
hutool库全面使用指南
android·java·算法·加解密·国密·sm4
前进的程序员1 个月前
OpenSSL加解密原理及使用方法详解
ssl·加解密·openssl
未来之窗软件服务2 个月前
幽冥大陆(六十六) PHP8.x SSL 文字解密—东方仙盟古法结界
ssl·加解密·仙盟创梦ide·东方仙盟
未来之窗软件服务2 个月前
幽冥大陆(六十五) PHP6.x SSL 文字解密—东方仙盟古法结界
网络·数据库·ssl·加解密·仙盟创梦ide·东方仙盟
未来之窗软件服务2 个月前
幽冥大陆(六十四) PHP7.0 SSL 文字解密—东方仙盟筑基期
php·ssl·加解密·仙盟创梦ide·东方仙盟
Ytadpole5 个月前
客户端加密 和 服务端加密:端到端安全的真正含义
安全·加解密
qqxhb6 个月前
系统架构设计师备考第20天——信息加解密技术&密钥管理技术
系统架构·des·aes·加解密·rsa·密钥管理·kdc
阿捏利7 个月前
【加解密与C】CRC128
c语言·加解密·crc·crc128
阿捏利7 个月前
【加解密与C】HASH系列(四)SHA-3
c语言·加解密·sha-3
阿捏利8 个月前
【加解密与C】非对称加解密(二)ELGamel
c语言·加解密·elgamel