DES加解密文件

</pre><pre name="code" class="java">import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;


import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;


/**
 * 3DES加密
 * 
 * @version 1.0
 * @author
 * 
 */
public abstract class DesUtil {
	 
	
	/**
	 * 密钥算法
	 * @version 1.0
	 * @author
	 */
	public static final String KEY_ALGORITHM = "DESede";
		
	/**
	 * 加密/解密算法/工作模式/填充方式
	 * @version 1.0
	 * @author
	 */	
	public static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
		
	/**
	 * 转换密钥
	 * @param key 二进制密
	 * @return key 密钥
	 * 
	 */	
	public static Key toKey(byte[] key) throws Exception{
		//实例化DES密钥材料
		DESedeKeySpec dks = new DESedeKeySpec(key);
		//实例化秘密密钥工
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
		//生成秘密密钥
		return keyFactory.generateSecret(dks);
	}


	/**
	 * 解密
	 * @param data 待解密数
	 * @param key 密钥
	 * @return byte[] 解密数据
	 */	
	public static byte[] decrypt(byte[] data, byte[] key)throws Exception{
		//还原密钥
		Key k = toKey(key);
		/**
		 * 实例
		 * 使用PKCS7Padding填充方式,按如下代码实现
		 * Cipher.getInstance(CIPHER_ALGORITHM,"BC");
		 */
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		//初始化,设置为解密模
		cipher.init(Cipher.DECRYPT_MODE, k);
		//执行操作
		return cipher.doFinal(data);
	}
	
	/**
	 * 加密
	 * @param data 待加密数
	 * @param key 密钥
	 * @return byte[] 加密数据
	 */	
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
		//还原密钥
		Key k = toKey(key);
		/**
		 * 实例
		 * 使用PKCS7Padding填充方式,按如下代码实现
		 * Cipher.getInstance(CIPHER_ALGORITHM,"BC");
		 */
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		//初始化,设置为解密模
		cipher.init(Cipher.ENCRYPT_MODE, k);
		//执行操作
		return cipher.doFinal(data);
	}
	
	/**
	 * 生成密钥
	 * 
	 * @return byte[] 二进制密
	 */	
	public static byte[] initKey() throws Exception{
		/**
		 * 实例
		 * 使用128位或192位长度密
		 * KeyGenerator.getInstance(KEY_ALGORITHM,"BC");
		 */
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		/**
		 * 初始
		 *使用128位或192位长度密钥,按如下代码实
		 *kg.init(128);
		 *kg.init(192);
		 */
		kg.init(168);
		//生成秘密密钥
		SecretKey secretKey = kg.generateKey();
		//获得密钥的二进制编码形式
		return secretKey.getEncoded();
	}


    /** 
     * <p>DES加密文件 
     * @param file 源文件 
     * @param destFile 加密后的文件 
     * @throws Exception 
     */  
    public static void encrypt(byte[] key,String file, String destFile) throws Exception {  
    	    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 
            //还原密钥
    		Key k = toKey(key);
            cipher.init(Cipher.ENCRYPT_MODE, k);  
            InputStream is = new FileInputStream(file);  
            OutputStream out = new FileOutputStream(destFile);  
            CipherInputStream cis = new CipherInputStream(is, cipher);  
            byte[] buffer = new byte[1024];  
            int r;  
            while ((r = cis.read(buffer)) > 0) {  
                out.write(buffer, 0, r);  
            }  
            cis.close();  
            is.close();  
            out.close();  
        }  
    
    
    /** 
     * <p> DES解密文件 
     * @param file 需要解密的文件 
     * @param dest 解密后的文件 
     * @throws Exception 
     */  
    public static void decrypt(byte[] key,String file, String dest) throws Exception {  
    	Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key k = toKey(key);
        cipher.init(Cipher.DECRYPT_MODE, k);  
        InputStream is = new FileInputStream(file);  
        OutputStream out = new FileOutputStream(dest);  
        CipherOutputStream cos = new CipherOutputStream(out, cipher);  
        byte[] buffer = new byte[1024];  
        int r;  
        while ((r = is.read(buffer)) >= 0) {  
            cos.write(buffer, 0, r);  
        }  
        cos.close();  
        out.close();  
        is.close();  
    } 
    
	/**
	 * 
	 * @param key 加密私钥
	 * @param fis 加密的文件输入流(原文件)
	 * @param out 加密的文件输出流(加密文件文件)
	 * @throws Exception
	 */
    public static void encrypt(byte[] key,InputStream fis, OutputStream out) throws Exception {  
    	    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 
            //还原密钥
    		Key k = toKey(key);
            cipher.init(Cipher.ENCRYPT_MODE, k);  
            CipherInputStream cis = new CipherInputStream(fis, cipher);  
            byte[] buffer = new byte[1024];  
            int r;  
            while ((r = cis.read(buffer)) > 0) {  
                out.write(buffer, 0, r);  
            }  
            cis.close();  
            fis.close();  
            out.close();  
        }  
    
	/**
	 * 
	 * @param key 加密私钥
	 * @param fis 加密后的文件输入流(加密后文件)
	 * @param out 解密的文件输出流(解密后文件)
	 * @throws Exception
	 */
    public static void decrypt(byte[] key,FileInputStream fis, OutputStream out) throws Exception {  
    	Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key k = toKey(key);
        cipher.init(Cipher.DECRYPT_MODE, k);  
        CipherOutputStream cos = new CipherOutputStream(out, cipher);  
        byte[] buffer = new byte[1024];  
        int r;  
        while ((r = fis.read(buffer)) >= 0) {  
            cos.write(buffer, 0, r);  
        }  
        cos.close();  
        out.close();  
        fis.close();  
    } 
    
    public static void main(String[] args) throws Exception {
//    	String key = "DooyI/e/aDRG3PjgwrCYzYCtGQSexNbs";
    	String key= "MzI5MTQ4NjVhMDE2M2YwOTNkZTQ3ZWM2ZGMyN2JlYzQ=";
//		String key=Base64.encodeBase64String(initKey());
		System.out.println(key);
//		System.out.println(key2);
    	 try {
			DesUtil.encrypt(key.getBytes(),"D:\\gw.jpg", "D:\\gw1.jpg");
			DesUtil.decrypt(key.getBytes(),"D:\\gw1.jpg","D:\\gw2.jpg");  
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
    
}


调用实例

加密

		//图片加密
			String key=Encodes.decodeBase64String(String.valueOf(CacheUtils.get(CryptUtils.AES_KEY)));
			try {
				  InputStream is = mf.getInputStream();  
		          OutputStream out = new FileOutputStream(tempFilePath);  
				DesUtil.encrypt(key.getBytes(), is, out);
			} catch (Exception e) {
				logger.info("图片:"+filePath+"加密出错");
				e.printStackTrace();
			}


解密

	@RequestMapping(value = "getImg")
	public void getImg(String filePath, HttpServletRequest request, HttpServletResponse response) {
		FileInputStream fis = null;
		if(filePath.toLowerCase().endsWith(".pdf")){
			response.setContentType("application/pdf;charset=UTF-8");
		}else{
			response.setContentType("application/octet-stream;charset=UTF-8");
		}
		
		try {
			OutputStream out = response.getOutputStream();
//			filePath="D:\\gw11.jpg";
			File file = new File(filePath);
			fis = new FileInputStream(file);
			//对文件解密
//			String key = "DooyI/e/aDRG3PjgwrCYzYCtGQSexNbs";
			String key=Encodes.decodeBase64String(String.valueOf(CacheUtils.get(CryptUtils.AES_KEY)));
			DesUtil.decrypt(key.getBytes(),fis,out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值