1. 程式人生 > >Java 3DES加密解密(Commons.Codec Base64)

Java 3DES加密解密(Commons.Codec Base64)

依賴包

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.binary.Base64;


演算法程式碼

 /**
     * 轉換成十六進位制字串
     * @param username
     * @return
     *
     * lee on 2017-08-09 10:54:19
     */
    public static byte[] hex(String key){  
        String f = DigestUtils.md5Hex(key);  
        byte[] bkeys = new String(f).getBytes();  
        byte[] enk = new byte[24];  
        for (int i=0;i<24;i++){  
            enk[i] = bkeys[i];  
        }  
        return enk;  
    }
    
    /**
     * 3DES加密
     * @param key 金鑰,24位
     * @param srcStr 將加密的字串
     * @return
     *
     * lee on 2017-08-09 10:51:44
     */
    public static String  encode3Des(String key,String srcStr){  
    	byte[] keybyte = hex(key);
    	byte[] src = srcStr.getBytes();
        try {  
           //生成金鑰  
           SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
           //加密  
           Cipher c1 = Cipher.getInstance("DESede");
           c1.init(Cipher.ENCRYPT_MODE, deskey);  
           
           String pwd = Base64.encodeBase64String(c1.doFinal(src));
//           return c1.doFinal(src);//在單一方面的加密或解密  
           return pwd;
       } catch (java.security.NoSuchAlgorithmException e1) {  
           // TODO: handle exception  
            e1.printStackTrace();  
       }catch(javax.crypto.NoSuchPaddingException e2){  
           e2.printStackTrace();  
       }catch(java.lang.Exception e3){  
           e3.printStackTrace();  
       }  
       return null;  
   }
    
   /**
    * 3DES解密
    * @param key 加密金鑰,長度為24位元組  
    * @param desStr 解密後的字串
    * @return
    *
    * lee on 2017-08-09 10:52:54
    */ 
    public static String decode3Des(String key, String desStr){  
    	Base64 base64 = new Base64();
    	byte[] keybyte = hex(key);
    	byte[] src = base64.decode(desStr);
    			
        try {  
            //生成金鑰  
            SecretKey deskey = new SecretKeySpec(keybyte, "DESede");  
            //解密  
            Cipher c1 = Cipher.getInstance("DESede");  
            c1.init(Cipher.DECRYPT_MODE, deskey);  
            String pwd = new String(c1.doFinal(src));
//            return c1.doFinal(src);  
            return pwd;
        } catch (java.security.NoSuchAlgorithmException e1) {  
            // TODO: handle exception  
            e1.printStackTrace();  
        }catch(javax.crypto.NoSuchPaddingException e2){  
            e2.printStackTrace();  
        }catch(java.lang.Exception e3){  
            e3.printStackTrace();  
        }  
        return null;          
    }

呼叫
String key = "xUHdKxzVCbsgVIwTnc1jtpWn";
		String idcard = "130682199606071234";
		String encode = PasswordUtil.encode3Des(key, idcard);
		log.info("原串:" + idcard);
		log.info("加密後的串:" + encode);
		log.info("解密後的串:" + PasswordUtil.decode3Des(key, encode));

輸出