All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.afu.utils.encryption.DESFileEncryption Maven / Gradle / Ivy

There is a newer version: 0.0.55-RELEASE
Show newest version
package io.afu.utils.encryption;

import io.afu.utils.exception.BaseException;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.spi.LoggerContextFactory;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

public class DESFileEncryption {


    public DESFileEncryption(String keyStr) {
        genKey(keyStr);
        initCipher();
    }

    private Key key;
    // 解密密码
    private Cipher cipherDecrypt;
    // 加密密码
    private Cipher cipherEncrypt;

    public final String CIPHER_ALGORITHM = "DES";


    /**
     * 加密文件的核心
     *
     * @param srcFileName
     *            要加密的文件
     * @param destFileName
     *            加密后存放的文件名
     * @return boolean 是否加密成功
     */
    public boolean encryptFile(String srcFileName, String destFileName) {
        try {
            InputStream is = new FileInputStream(srcFileName);
            OutputStream out = new FileOutputStream(destFileName);

            CipherInputStream cis = new CipherInputStream(is, cipherEncrypt);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = cis.read(buffer)) > 0) {
                out.write(buffer, 0, r);
            }
            cis.close();
            is.close();
            out.close();
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /***
     * 解密文件
     *
     * @param fileName 文件名(包含具体路劲)
     * @return List 返回的字符串列表
     */
    public List decryptFileContent(String fileName) {
        List list = new ArrayList();
        try {
            InputStream is = new FileInputStream(fileName);
            CipherInputStream cis = new CipherInputStream(is, cipherDecrypt);
            BufferedReader reader = new BufferedReader(new InputStreamReader(cis));
            String line = null;
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
            reader.close();
            cis.close();
            is.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public void decryptFileContent(String fileName,String dstFilePath){
        try {
            InputStream is = new FileInputStream(fileName);
            CipherInputStream cis = new CipherInputStream(is, cipherDecrypt);
            BufferedReader reader = new BufferedReader(new InputStreamReader(cis));
            FileWriter fileWriter = new FileWriter(dstFilePath);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            String line = null;
            while ((line = reader.readLine()) != null) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
            bufferedWriter.close();
            reader.close();
            cis.close();
            is.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 解密文件,返回reader
     * @param fileName 文件名字(包含具体路径)
     * @return BufferedReader
     */
    public BufferedReader decryptFile(String fileName) {
        BufferedReader reader = null;
        try {
            InputStream is = new FileInputStream(fileName);
            CipherInputStream cis = new CipherInputStream(is, cipherDecrypt);
            reader = new BufferedReader(new InputStreamReader(cis));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return reader;
    }


    private void initCipher() {
        try {
            // 加密的cipher
            cipherEncrypt = Cipher.getInstance(CIPHER_ALGORITHM);
            cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);
            // 解密的cipher
            cipherDecrypt = Cipher.getInstance(CIPHER_ALGORITHM);
            cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 自定义一个key
     *
     * @param keyRule 加密的key规则
     */
    public void genKey(String keyRule) {
        // Key key = null;
        byte[] keyByte = keyRule.getBytes();
        // 创建一个空的八位数组,默认情况下为0
        byte[] byteTemp = new byte[8];
        // 将用户指定的规则转换成八位数组
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
            byteTemp[i] = keyByte[i];
        }
        key = new SecretKeySpec(byteTemp, "DES");
    }

    /**
     * DES 加密字符串
     * @param data 需要被加密的字符串
     * @return 返回Base64加密后的内容
     * @throws BaseException 抛错
     */
    public String encrypt(String data) throws BaseException {
        try {

            byte[] result = cipherEncrypt.doFinal(data.getBytes());
            return new String(Base64.encodeBase64(result),StandardCharsets.UTF_8);
        }catch (Exception e){
            throw new BaseException(e);
        }
    }

    public String DESEncrypt(String data) throws BaseException  {
        try {
            byte[] results = cipherEncrypt.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return new String(results,StandardCharsets.UTF_8);
        }catch (Exception e){
            throw new BaseException(e);
        }
    }

    /**
     * DES解密
     * @param data 需要解密的字符串(是上面已经Base64加密过的串)
     * @return 解密后的内容,如果解密失败,则返回原始内容
     * @throws BaseException 抛错
     */
    public String decrypt(String data) throws BaseException {
        try {
            if (data == null){
                return null;
            }
            String result = null;
            try {
                BASE64Decoder base64Decoder = new BASE64Decoder();
                byte[] buf = base64Decoder.decodeBuffer(data);
                String bu = DesDecrypt(buf);
                result = bu;
            }catch (Exception e){
                throw new BaseException(e);
            }
            return result;
        }catch (Exception e){
            return data;
        }
    }

    public  String DesDecrypt(byte[] data) throws BaseException {
        String result = null;
        try {
            byte[] rel = cipherDecrypt.doFinal(data);
            result = new String(rel, StandardCharsets.UTF_8);
        }catch (Exception e){
            throw new BaseException(e);
        }
        return result;
    }


    /***
     * 测试加密解密
     *
     * @param args 命令行传入的参数
     */
    public static void main(String[] args) {
//        DESFileEncryption deEncrypt = new DESFileEncryption("STP FILE DE-ENCRYPT");
//        deEncrypt.encryptFile("D:\\tmp\\T20180913044001.xml", "D:\\tmp\\T20180913044001.bin");
//        try {
//            String originMd5 = Md5Encryption.md5(new File("D:\\tmp\\T20180913044001.xml"));
//            System.out.println("args = [" + originMd5 + "]");
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//        List list = deEncrypt.decryptFileContent("D:\\tmp\\T20180913044001.bin");
//        deEncrypt.decryptFileContent("D:\\tmp\\T20180913044001.bin","D:\\tmp\\23333.xml");
//        try {
//            String resultMd5 = Md5Encryption.md5(new File("D:\\tmp\\23333.xml"));
//            System.out.println("args = [" + resultMd5 + "]");
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        for (String str : list) {
//            System.out.println(str);
//        }



    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy