分享一份Java中加密的代码

之前有学习加密相关技术,Java的crypto包可以支持常用的加密,但是没有完整并且准确的示例,同时在加密文件时也有很多问题。发一份完整代码,支持文件加密等等。


package com.common.crypt;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;


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


import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**


 * @version 1.0


 */


public class DesCryptCoder {


    /**


     * 转换的名称


     * 由于是流式加密,其反馈模式部分应为字节型CFB8/OFB8填充部分应为NoPadding,注意是NoPadding,不然文件流在加解密过程中会出现多余的字节,导致文件内容发      *生变化


     */


    private static final String Transformation = "DES/CFB8/NoPadding";


    /**


     * 加解密使用的算法名称


     */


    private static final String Algorithm = "DES";


    /**


     * 加密使用的默认密钥


     */


    private static final byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 };


    /**


     * 加密使用的默认密钥


     */


    private static final byte[] param_key = { 9, 10, 11, 12, 13, 14, 15, 16 };


    private static final Logger logger = LoggerFactory


    .getLogger(DesCryptCoder.class);


    /**


     * 返回加解密过程使用的密钥


     * 


     * @return 加密密钥


     */


    private Key getKey() {
        return new SecretKeySpec(key, Algorithm);


    }


    /**


     * 获得一个信息加密和解密的功能对象,


     * 


     * @return Cipher对象


     */


    private Cipher newCipher() {


        try {


            return Cipher.getInstance(Transformation);


        } catch (NoSuchAlgorithmException e) {


            logger.error(String.format("当前Java环境不支持该加密算法:%s", Transformation),


            e);


        } catch (NoSuchPaddingException e) {


            logger.error(String.format("当前Java环境不支持该填充算法:%s", Transformation),


            e);


        }


        return null;


    }


    /**


     * 获得加密的Cipher对象


     * 


     * @return 加密的Cipher对象


     */


    private Cipher getEncryptCipher() {


        return newEncryptCipher();


    }


    /**


     * 初始化加密的Cipher成员变量ecipher


     * 


     * @return 加密使用的功能对象ecipher


     */


    private synchronized Cipher newEncryptCipher() {


        try {


            Cipher ecipher = newCipher();


            if (ecipher != null) {


                javax.crypto.spec.IvParameterSpec ips = new javax.crypto.spec.IvParameterSpec(
                        param_key);


                ecipher.init(Cipher.ENCRYPT_MODE, getKey(), ips);


            }


            return ecipher;


        } catch (InvalidKeyException e) {


            logger.error("密钥无效,无法构造Cipher类!", e);


        } catch (InvalidAlgorithmParameterException e) {
            logger.error("密钥无效,无法构造Cipher类!", e);
        }


        return null;


    }


    /**


     * 获得解密的功能对象Cipher


     * 


     * @return 解密使用的功能对象dcipher


     */


    private Cipher getDecryptCipher() {


        return newDecryptCipher();


    }


    /**


     * 初始化成员变量:解密功能对象dcipher


     * 


     * @return 解密功能对象dcipher


     */


    private synchronized Cipher newDecryptCipher() {


        try {


            Cipher dcipher = newCipher();


            if (dcipher != null) {


                javax.crypto.spec.IvParameterSpec ips = new javax.crypto.spec.IvParameterSpec(
                        param_key);
                dcipher.init(Cipher.DECRYPT_MODE, getKey(), ips);


            }


            return dcipher;


        } catch (InvalidKeyException e) {


            logger.error("密钥无效,无法构造Cipher类!", e);


        } catch (InvalidAlgorithmParameterException e) {
            logger.error("密钥无效,无法构造Cipher类!", e);
        }


        return null;


    }


    public OutputStream encode(OutputStream os) {


        Cipher cipher = getEncryptCipher();


        if (cipher != null) {


            return new CipherOutputStream(os, cipher);


        }


        return os;


    }


    public InputStream decode(InputStream is) {


        Cipher cipher = getDecryptCipher();


        if (cipher != null) {


            return new CipherInputStream(is, cipher);


        }


        return is;


    }


    public static void main(String[] args) {


        encode();


        decode();


    }


    public static void encode() {


        InputStream ip = null;


        OutputStream op = null;


        OutputStream deIp = null;


        try {


            DesCryptCoder coder = new DesCryptCoder();


            ip = new FileInputStream("E:/encryptDe.txt");


            op = new FileOutputStream("E:/encryptDe1.txt");


            deIp = coder.encode(op);


            int i;


            byte[] buffer = new byte[1024];


            while ((i = ip.read(buffer)) != -1) {


                deIp.write(buffer, 0, i);


            }


            op.flush();


        } catch (Exception e) {


            logger.error("加密出错", e);


        } finally {


            IOUtils.closeQuietly(ip);


            IOUtils.closeQuietly(op);


            IOUtils.closeQuietly(deIp);


        }


    }


    public static void decode() {


        InputStream ip = null;


        OutputStream op = null;


        InputStream deIp = null;


        try {


            DesCryptCoder coder = new DesCryptCoder();


            ip = new FileInputStream("E:/encryptDe1.txt");


            op = new FileOutputStream("E:/encryptDe2.txt");


            deIp = coder.decode(ip);


            int i;


            byte[] buffer = new byte[1024];


            while ((i = deIp.read(buffer)) != -1) {


                op.write(buffer, 0, i);


            }


            op.flush();


        } catch (Exception e) {


            logger.error("解密出错", e);


        } finally {


            IOUtils.closeQuietly(ip);


            IOUtils.closeQuietly(op);


            IOUtils.closeQuietly(deIp);


        }


    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值