日期:2014-05-20 浏览次数:20946 次
import java.security.Key; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import biz.source_code.base64Coder.*; /** * @author Administrator * */ public class TripleDEService { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } private static String strkey = "d+KuEICNtJsujXBH23MU6AjAjheQhpqJ"; private static String Algorithm = "desede/ECB/PKCS5Padding"; /** * 加密String明文输入,String密文输出 * * @param input * @return */ public static String DesEncrypt(String input) { byte[] byteMi = null; byte[] byteMing = null; String strMi = ""; // BASE64Encoder base64en = new BASE64Encoder(); try { byteMing = input.getBytes("UTF-8"); byte[] key = Base64Coder.decode(strkey); // BASE64Decoder().decodeBuffer(strkey); byteMi = getEncCode(byteMing, key); strMi = Base64Coder.encodeLines(byteMi); // base64en.encode(byteMi); } catch (Exception e) { e.printStackTrace(); } finally { // base64en = null; byteMing = null; byteMi = null; } return strMi; } /** * 加密以byte[]明文输入,byte[]密文输出 * * @param byteS * @return */ private static byte[] getEncCode(byte[] byteS, byte[] key) { byte[] byteFina = null; Cipher cipher; try { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory .getInstance("desede"); deskey = keyfactory.generateSecret(spec); cipher = Cipher.getInstance(Algorithm); cipher.init(Cipher.ENCRYPT_MODE, deskey); byteFina = cipher.doFinal(byteS); } catch (Exception e) { e.printStackTrace(); } finally { cipher = null; } return byteFina; } /** * 解密 以String密文输入,String明文输出 * * @param input * @return */ public static String DesDecrypt(String input) { // BASE64Decoder base64De = new BASE64Decoder(); byte[] byteMing = null; byte[] byteMi = null; String strMing = ""; try { byteMi = Base64Coder.decode(input); // base64De.decodeBuffer(input); byte[] key = Base64Coder.decode(strkey); // new // BASE64Decoder().decodeBuffer(strkey); byteMing = getDesCode(byteMi, key); strMing = new String(byteMing, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { // base64De = null; byteMing = null; byteMi = null; } return strMing; } /** * 解密以byte[]密文输入,以byte[]明文输出 * * @param byteD * @return */ private static byte[] getDesCode(byte[] byteD, byte[] key) { Cipher cipher; byte[] byteFina = null; try { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory .getInstance("desede"); deskey = keyfactory.generateSecret(spec); cipher = Cipher.getInstance(Algorithm); cipher.init(Cipher.DECRYPT_MODE, deskey); byteFina = cipher.doFinal(byteD); } catch (Exception e) { e.printStackTrace(); } finally { cipher = null; } return byteFina; } }