/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: DesUtils.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	2016年10月31日
 */
package com.yihu.wlyy.util;


import org.apache.shiro.codec.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;


/**
 * 3des加密解密（base64）
 * @author: qigui.su
 * @version Revision: 0.0.1
 * @Date: 2016年10月31日
 */
public class DesUtils {

	 // 向量  
    private final static String iv = "01234567" ;  
    // 加解密统一使用的编码方式  
    private final static String encoding = "utf-8" ;  
       
    /** 
     * 3DES加密 
     * @author: qigui.su
     * @param plainText 内容
     * @param key 密匙不小于24
     * @return
     * @throws Exception
     */
    public static String encode(String plainText,String key) throws Exception {  
        Key deskey = null ;  
        DESedeKeySpec spec = new DESedeKeySpec(key.getBytes());  
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance( "DESede" );  
        deskey = keyfactory.generateSecret(spec);  
       
        Cipher cipher = Cipher.getInstance( "DESede/CBC/PKCS5Padding" );  
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());  
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);  
        byte [] encryptData = cipher.doFinal(plainText.getBytes(encoding));  
        return Base64.encodeToString(encryptData);
    }  
       
    /** 
     * 3des解密
     * @author: qigui.su
     * @param encryptText 内容
     * @param key 密匙不小于24位
     * @return
     * @throws Exception
     */
    public static String decode(String encryptText, String key) throws Exception {  
        Key deskey = null ;  
        DESedeKeySpec spec = new DESedeKeySpec(key.getBytes());   
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance( "DESede" );  
        deskey = keyfactory.generateSecret(spec);  
        Cipher cipher = Cipher.getInstance( "DESede/CBC/PKCS5Padding" );  
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());  
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);  
       
        byte [] decryptData = cipher.doFinal(Base64.decode(encryptText));  
       
        return new String(decryptData, encoding);  
    }  
}
