采用Cipher DES针对文件加密、解密

由于经常用一些加密或者解密文件的,所以写了一个简单的采用Cipher DES针对文件加密、解密的工具类,记录一下,防止以后忘记了! 

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/***
 * Des文件加密解密
 */
public class FileDeEncrypt {
    private static final Logger LOG = LoggerFactory.getLogger(FileDeEncrypt.class);


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

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


    /**
     * 加密文件的核心
     * 
     * @param file
     *            要加密的文件
     * @param destFile
     *            加密后存放的文件名
     */
    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();
            LOG.info("文件{}加密完成,加密后的文件是:{}", srcFileName, destFileName);
            return true;
        }
        catch (Exception e) {
            LOG.error("加密文件{}出现异常", srcFileName, e.getMessage());
            e.printStackTrace();
            return false;
        }
    }


    /***
     * 解密文件
     * 
     * @param destFile
     */
    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();
            LOG.info("文件{}解密完成", fileName);
        }
        catch (Exception e) {
            LOG.error("解密文件{}出现异常", fileName, e.getMessage());
            e.printStackTrace();
        }
        return list;
    }
    
    /**
     * 解密文件,返回reader
     * @param fileName
     * @return
     */
    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) {
            LOG.error("解密文件{}出现异常", fileName, e.getMessage());
            e.printStackTrace();
        }
        return reader;
    }


    private void initCipher() {
        try {
            // 加密的cipher
            cipherEncrypt = Cipher.getInstance("DES");
            cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);
            // 解密的cipher
            cipherDecrypt = Cipher.getInstance("DES");
            cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
        }
        catch (Exception e) {
            LOG.info("加密初始化出现异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 自定义一个key
     * 
     * @param string
     */
    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");
    }


    /***
     * 测试加密解密
     * 
     * @param args
     */
    public static void main(String[] args) {
        FileDeEncrypt deEncrypt = new FileDeEncrypt("STP FILE DE-ENCRYPT");
        deEncrypt.encryptFile("pom.xml", "pom.bin");
        List list = deEncrypt.decryptFileContent("pom.bin");
        for (String str : list) {
            System.out.println(str);
        }
    }
}

---------------------------------------------------------------------

作者:cloud-coder 

来源:开源中国

链接:https://my.oschina.net/cloudcoder/blog/648682

 

下面是我个人写的流加密工具

package com.brillilab.common.utils;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 流加解密工具
 *
 * @author wmh
 */
public class FileSecurityUtil {

    /**
     * 加密输入流
     *
     * @param in
     * @param secretKey
     * @return
     */
    public static InputStream encryptIputStream(InputStream in,String secretKey) {

        String tempKey=genTempKeyString(secretKey);

        Cipher cipher=initCipher(Cipher.ENCRYPT_MODE,tempKey);

        return new CipherInputStream(in,cipher);

    }

    /**
     * 解密输出流
     *
     * @param out
     * @param secretKey
     * @return
     */
    public static OutputStream decryptOutputStream(OutputStream out,String secretKey) {

        String tempKey=genTempKeyString(secretKey);

        Cipher cipher=initCipher(Cipher.DECRYPT_MODE,tempKey);

        return new CipherOutputStream(out,cipher);
    }

    /**
     * 加密器
     *
     * @param cipherModel
     * @param keyRule
     * @return
     */
    private static Cipher initCipher(int cipherModel,String keyRule) {


        try {
            byte[] keyBytes=keyRule.substring(0,8).getBytes("ASCII");
            byte[] IVBytes=keyRule.substring(8,16).getBytes("ASCII");

            SecretKeySpec key=new SecretKeySpec(keyBytes,"DES");
            IvParameterSpec IV=new IvParameterSpec(IVBytes);

            Cipher cipher=Cipher.getInstance("DES/CBC/NoPadding");
            cipher.init(cipherModel,key,IV);
            return cipher;
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException |
                InvalidAlgorithmParameterException | NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取临时key
     * @param keyStr
     * @return
     */
    private static String genTempKeyString(String keyStr) {
        Assert.isTrue(!StringUtils.isEmpty(keyStr) && keyStr.length() == 16,"keyStr must be formed with 16 characters");
        String tempKey=null;
        tempKey=keyStr.substring(14,16) + keyStr.substring(0,2) + keyStr.substring(10,12) + keyStr.substring(8,10);
        tempKey+=keyStr.substring(12,14) + keyStr.substring(6,8) + keyStr.substring(2,4) + keyStr.substring(4,6);
        return tempKey;
    }
}

可以直接拿去使用,有感兴趣的小伙伴也可以自己写一下,只是简单的 javax.crypto.Cipher , java.security 包API的使用

你可能感兴趣的:(工具)