文件加解密处理类

本文介绍了一个实用的文件加密解密类,包括对二进制文件进行加密和解密的方法,并实现了MD5加密算法。通过特定的字节交换方式确保文件的安全性,同时提供了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package **.tool;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author AA 20190710
 * 文件加密解密类
 */
public class EncryptTools {
    /**
     * 加密标志第一位
     */
    private static final char FIRST = **;
    /**
     * 加密标志第二位
     */
    private static final char SECOND = ***;

    /**
     * 给二进制文件加密
     *
     * @param file 二进制文件
     * @return 加密后的二进制文件
     */
    public static byte[] encryptFile(byte[] file) {
        /*将字节数组的开始n位和对应的最后n位对调位置*/
        int len = file.length;
        int count = len > 100 ? 50 : file.length / 2;
        for (int i = 0; i < count; i++) {
            byte temp = file[i];
            file[i] = file[len - i - 1];
            file[len - i - 1] = temp;
        }
        //将加密后的数组前加上97、116(at)标识为已加密
        byte[] bytes = new byte[len + 2];
        System.arraycopy(file, 0, bytes, 2, len);
        bytes[0] = FIRST;
        bytes[1] = SECOND;
        return bytes;
    }

    /**
     * 给二进制文件解密
     *
     * @param file 加密的二进制文件
     * @return 解密后的二进制文件
     */
    public static byte[] decryptFile(byte[] file) {
        if (file == null || file.length == 0) {
            return file;
        }
        //判断是否为加密文件,是否以97和116开头,如果是加密文件则进行解密
        if (file[0] != FIRST || file[1] != SECOND) {
            return file;
        }
        //去掉开头两个标识字节
        byte[] bytes = new byte[file.length - 2];
        System.arraycopy(file, 2, bytes, 0, file.length - 2);
        //将数组的开始和结束位置数对调
        int len = bytes.length;
        int count = len > 100 ? 50 : len / 2;
        for (int i = 0; i < count; i++) {
            byte temp = bytes[i];
            bytes[i] = bytes[len - i - 1];
            bytes[len - i - 1] = temp;
        }
        return bytes;
    }

    /**
     * MD5加密
     *
     * @param plainText
     * @return
     */
    public static String MD5Encrypt(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法!");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值