package cn.com.lzt.message.send.util; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.Key; /** * 3DES加密工具类 */ public class Des3 { // 加解密统一使用的编码方式 private final static String encoding = "UTF-8"; private static String ENCODE_KEY = "r_s@3+jj,9_?.cv<_u!@sd1ee"; private static String ENCODE_IV = "15801445"; /** * 3DES加密 * * @param text * 普通文本 * @return * @throws Exception */ public static String encode(String text,String key,String iv) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(encoding)); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(iv.getBytes(encoding)); cipher.init(Cipher.ENCRYPT_MODE, deskey, ips); byte[] encryptData = cipher.doFinal(text.getBytes(encoding)); return URLEncoder.encode(Base64.encode(encryptData),encoding); } public static String encode(String text) throws Exception { return encode(text,ENCODE_KEY,ENCODE_IV); } public static String decode(String encryptText,String key,String iv) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(encoding)); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(iv.getBytes(encoding)); cipher.init(Cipher.DECRYPT_MODE, deskey, ips); byte[] decryptData = cipher.doFinal(Base64.decode(encryptText)); return new String(decryptData, encoding); } public static String decode(String encryptText) throws Exception { return decode(encryptText,ENCODE_KEY,ENCODE_IV); } }