java使用原生的DES算法实现任意的文件加密解密

最近由于项目要求:制卡文件在传输之前,需要进行加密(由于是银行项目,所以为了安全起见),然后发送给下游制卡厂商,加密方式不作要求,符合新一代加密规范即可。经过一番的资料查找,发现目前主流的文件加密有:DES、AES等对称加密,这种加密方式相对来说比较安全,成熟,稳定、可靠。所以暂时选择了DES加密,具体加密/解密代码如下:

package com.laozeng.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Properties;


/**
 * 参考路径:http://t.zoukankan.com/i-tao-p-14518934.html
 * 使用DES进行简单的文件加密,解密
 */
public class FileDESUtil {
    private static final Log logger = LogFactory.getLog(FileDESUtil.class);
    private static final String SLAT_KEY = "1234567890";
    private String algorithm;
    private Key key;

    public static synchronized FileDESUtil getInstance() {
        if (instance == null) {
            instance = new FileDESUtil();
        }
        return instance;
    }

    private static FileDESUtil instance;

    private FileDESUtil() {
        // 初始化algorithm
        initAlgorithm();

        //生成密匙
        initKey();
    }

    private void initAlgorithm() {
        try {
            Properties properties = new Properties();
            properties.load(FileDESUtil.class.getResourceAsStream("/des.properties"));
            algorithm = properties.getProperty("algorithm");
            algorithm = "DES";
        } catch (Exception e) {
            algorithm = "DES";
            logger.warn("des.properties is not config, algorithm was config = DES");
        }
    }

    private void initKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
            keyGenerator.init(new SecureRandom(SLAT_KEY.getBytes()));
            this.key = keyGenerator.generateKey();
        } catch (Exception e) {
            logger.error("createKey error: " + e);
        }
    }

    /**
     * 文件加密
     * @param file
     * @param destFile
     * @throws Exception
     */
    public void encrypt(String file, String destFile) {
        try (InputStream is = new FileInputStream(file);
             OutputStream out = new FileOutputStream(destFile)) {

            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, this.key);
            try (CipherInputStream cis = new CipherInputStream(is, cipher)) {
                byte[] buffer = new byte[1024];
                int r;
                while ((r = cis.read(buffer)) > 0) {
                    out.write(buffer, 0, r);
                    out.flush();
                }
            }
            logger.info(String.format("encrypt is over,file:%s,destFile:%s", file, destFile));
        } catch (Exception e) {
            logger.error("encrypt is error:", e);
        }
    }

    /**
     * 文件解密
     * @param file
     * @param dest
     * @throws Exception
     */
    public void decrypt(String file, String dest) {
        try (InputStream is = new FileInputStream(file);
             OutputStream out = new FileOutputStream(dest)) {

            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.DECRYPT_MODE, this.key);
            try (CipherOutputStream cos = new CipherOutputStream(out, cipher)) {
                byte[] buffer = new byte[1024];
                int r;
                while ((r = is.read(buffer)) >= 0) {
                    cos.write(buffer, 0, r);
                }
            }
            logger.info(String.format("decrypt is over,file:%s,destFile:%s", file, dest));
        } catch (Exception e) {
            logger.error("decrypt is error:", e);
        }
    }

    public static void main(String[] args) {
        FileDESUtil.getInstance().encrypt("d:/demo.rar", "d:/demoDES1.rar");
        FileDESUtil.getInstance().decrypt("d:/demoDES1.rar", "d:/demo1.rar");
    }
}

加密效果如下(说明:demoDES1.rar是加密过后的文件,可以发现已经打不开了,demo1.rar是解密后的文件,可以正常打开):

java使用原生的DES算法实现任意的文件加密解密_第1张图片

 

代码说明:

1.由于是工具类,所以简单的写了一个单例模式的调用方法,目前粗暴的使用了synchronized同步代码块的关键字来实现线程安全

2.由于工程需要经过sonar检测(直接赋值algorithm="DES"这种方式代码检测不让通过),所以提出了一个initAlgorithm方法用于初始化algorithm变量,其中des.properties文件需要放在classpath下面,才能够被读取到

你可能感兴趣的:(java,算法,开发语言,DES)