原文地址: http://www.cnblogs.com/lianghuilin/archive/2013/04/15/3DES.html
1 package my3des; 2 3 import java.io.UnsupportedEncodingException; 4 5 import javax.crypto.Cipher; 6 import javax.crypto.SecretKey; 7 import javax.crypto.spec.SecretKeySpec; 8 9 10 /** 11 * SecretUtils {3DES加密解密的工具类 } 12 * @author William 13 * @date 2013-04-19 14 */ 15 public class SecretUtils { 16 17 //定义加密算法,有DES、DESede(即3DES)、Blowfish 18 private static final String Algorithm = "DESede"; 19 private static final String PASSWORD_CRYPT_KEY = "2012PinganVitality075522628888ForShenZhenBelter075561869839"; 20 21 22 /** 23 * 加密方法 24 * @param src 源数据的字节数组 25 * @return 26 */ 27 public static byte[] encryptMode(byte[] src) { 28 try { 29 SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm); //生成密钥 30 Cipher c1 = Cipher.getInstance(Algorithm); //实例化负责加密/解密的Cipher工具类 31 c1.init(Cipher.ENCRYPT_MODE, deskey); //初始化为加密模式 32 return c1.doFinal(src); 33 } catch (java.security.NoSuchAlgorithmException e1) { 34 e1.printStackTrace(); 35 } catch (javax.crypto.NoSuchPaddingException e2) { 36 e2.printStackTrace(); 37 } catch (java.lang.Exception e3) { 38 e3.printStackTrace(); 39 } 40 return null; 41 } 42 43 44 /** 45 * 解密函数 46 * @param src 密文的字节数组 47 * @return 48 */ 49 public static byte[] decryptMode(byte[] src) { 50 try { 51 SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm); 52 Cipher c1 = Cipher.getInstance(Algorithm); 53 c1.init(Cipher.DECRYPT_MODE, deskey); //初始化为解密模式 54 return c1.doFinal(src); 55 } catch (java.security.NoSuchAlgorithmException e1) { 56 e1.printStackTrace(); 57 } catch (javax.crypto.NoSuchPaddingException e2) { 58 e2.printStackTrace(); 59 } catch (java.lang.Exception e3) { 60 e3.printStackTrace(); 61 } 62 return null; 63 } 64 65 66 /* 67 * 根据字符串生成密钥字节数组 68 * @param keyStr 密钥字符串 69 * @return 70 * @throws UnsupportedEncodingException 71 */ 72 public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException{ 73 byte[] key = new byte[24]; //声明一个24位的字节数组,默认里面都是0 74 byte[] temp = keyStr.getBytes("UTF-8"); //将字符串转成字节数组 75 76 /* 77 * 执行数组拷贝 78 * System.arraycopy(源数组,从源数组哪里开始拷贝,目标数组,拷贝多少位) 79 */ 80 if(key.length > temp.length){ 81 //如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中 82 System.arraycopy(temp, 0, key, 0, temp.length); 83 }else{ 84 //如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中 85 System.arraycopy(temp, 0, key, 0, key.length); 86 } 87 return key; 88 } 89 }
1 package my3des; 2 3 public class Main { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 String msg = "3DES加密解密案例"; 10 System.out.println("【加密前】:" + msg); 11 12 //加密 13 byte[] secretArr = SecretUtils.encryptMode(msg.getBytes()); 14 System.out.println("【加密后】:" + new String(secretArr)); 15 16 //解密 17 byte[] myMsgArr = SecretUtils.decryptMode(secretArr); 18 System.out.println("【解密后】:" + new String(myMsgArr)); 19 } 20 }