java 加密或解密文件名并设置为系统隐藏文件

java 加密或解密文件名并设置为系统隐藏文件

  • 系统隐藏文件:在windows文件管理器中隐藏或取消隐藏,通过attrib +s +h 文件路径attrib -s -h 文件路径命令实现
  • 加解密文件名:Base64 + 串行化 加密

1.实现代码

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@Slf4j
@Component
public class UpdateFileUtil {

    public static final String ENCODE = "encode";
    public static final String DECODE = "decode";

    /**
     * 键盘录入 加解密文件
     */
    public static void doEncry() {

        log.info("\n=================== begin ===================");
        Scanner scanner = new Scanner(System.in);
        log.info("\nnextLine(filePath): ");
        String path = scanner.nextLine();
        log.info("\nnextLine(type 0-encode,1-decode): ");
        String type = scanner.nextLine();

        File file = new File(path);
        String newType = "0".equals(type) ? ENCODE : ("1".equals(type) ? DECODE : "");
        boolean resFlagByName = encryFileName(newType, file);

        boolean resFlagByAttrib = false;
        if (resFlagByName) {
            resFlagByAttrib = setAttrib(newType, file);
        }

        log.info("\n=================== end ({})===================s", resFlagByAttrib);
    }

    /**
     * 加解密文件
     * @param type
     * @param filePath
     */
    public static boolean encryFileName(String type, File filePath) {
        log.debug("begin! type = {}, filePath = {}.", type, filePath);
        boolean flag = false;
        if (!filePath.exists()) {
            log.debug("file is not exists!");
            return flag;
        }
        if (filePath.isFile()) {
            File newFile = getNewFile(type, filePath);
            if (newFile == null) {
                log.debug("rename file is fail!");
                return flag;
            }
            boolean isRename = filePath.renameTo(newFile);
            if (isRename) {
                flag = setAttrib(type, filePath);
                log.debug("update File: {}, {}.", flag, filePath);
            }
        } else if (filePath.isDirectory()) {
            File[] files = filePath.listFiles();
            for (int i = 0; i < files.length; i++) {
                File newFile = files[i];
                boolean resFlag = encryFileName(type, newFile);
                if (resFlag) {
                    flag = setAttrib(type, newFile);
                }
            }
        }
        log.debug("end.");
        return flag;
    }

    /**
     * 配置重命名后的文件路径
     * @param type
     * @param filePath
     * @return
     */
    private static File getNewFile(String type, File filePath) {
        String newFileName = formatFileName(type, filePath);
        if (newFileName == null || "".equals(newFileName)) {
            log.debug("file is not exists!");
            return null;
        }

        String oldFilePath = filePath.getPath().replaceAll("\\\\", "/");
        String newFilePath = oldFilePath.substring(0, oldFilePath.lastIndexOf("/")).replaceAll("\\\\", "/");
        newFilePath = (!"".equals(newFilePath) && !newFilePath.endsWith("/")) ? newFilePath + "/" : newFilePath;
        if ("".equals(newFilePath)) {
            log.debug("file is not exists!");
            return null;
        }
        return new File(newFilePath + newFileName);
    }

    /**
     * 设置文件或文件夹名称
     * @param type ENCODE 加密,DECODE 解密
     * @param filePath 文件
     * @return
     */
    private static String formatFileName(String type, File filePath) {
        String newFileName = null;
        if (ENCODE.equals(type)) {
            newFileName = Hex.encodeHexString(Base64.encodeBase64(filePath.getName().getBytes(StandardCharsets.UTF_8)));
        }
        if (DECODE.equals(type)) {
            byte[] decodeHex = null;
            try {
                char[] fileNameToChars = filePath.getName().toCharArray();
                decodeHex = Hex.decodeHex(fileNameToChars);
            } catch (DecoderException e) {
                log.debug("fileName format fail!,{}", e.getMessage());
            }
            if (null == decodeHex) {
                log.debug("fileName format to Hex fail!");
                return null;
            }
            byte[] decodeBase64 = Base64.decodeBase64(decodeHex);
            newFileName = null == decodeBase64 ? "" : new String(decodeBase64, StandardCharsets.UTF_8);
        }
        return newFileName;
    }

    /**
     * 设置文件或文件夹属性
     * R: 只读文件属性。A:存档文件属性。S:系统文件属性。H:隐藏文件属性
     * @param type 类型 添加或去除文件属性
     * @param file 文件
     */
    public static boolean setAttrib(String type, File file) {
        try {
            String attribCmd = ENCODE.equals(type) ? "attrib +s +h " : (DECODE.equals(type) ? "attrib -s -h " : "");
            String cmdStr = attribCmd + file.getAbsolutePath();
            Runtime.getRuntime().exec(cmdStr);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}

2.pom文件依赖项 (spring boot)

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值