Des3.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package cn.com.lzt.message.send.util;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.SecretKeyFactory;
  4. import javax.crypto.spec.DESedeKeySpec;
  5. import javax.crypto.spec.IvParameterSpec;
  6. import java.net.URLDecoder;
  7. import java.net.URLEncoder;
  8. import java.security.Key;
  9. /**
  10. * 3DES加密工具类
  11. */
  12. public class Des3 {
  13. // 加解密统一使用的编码方式
  14. private final static String encoding = "UTF-8";
  15. private static String ENCODE_KEY = "r_s@3+jj,9_?.cv<_u!@sd1ee";
  16. private static String ENCODE_IV = "15801445";
  17. /**
  18. * 3DES加密
  19. *
  20. * @param text
  21. * 普通文本
  22. * @return
  23. * @throws Exception
  24. */
  25. public static String encode(String text,String key,String iv) throws Exception {
  26. Key deskey = null;
  27. DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(encoding));
  28. SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
  29. deskey = keyfactory.generateSecret(spec);
  30. Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
  31. IvParameterSpec ips = new IvParameterSpec(iv.getBytes(encoding));
  32. cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
  33. byte[] encryptData = cipher.doFinal(text.getBytes(encoding));
  34. return URLEncoder.encode(Base64.encode(encryptData),encoding);
  35. }
  36. public static String encode(String text) throws Exception {
  37. return encode(text,ENCODE_KEY,ENCODE_IV);
  38. }
  39. public static String decode(String encryptText,String key,String iv) throws Exception {
  40. Key deskey = null;
  41. DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(encoding));
  42. SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
  43. deskey = keyfactory.generateSecret(spec);
  44. Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
  45. IvParameterSpec ips = new IvParameterSpec(iv.getBytes(encoding));
  46. cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
  47. byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));
  48. return new String(decryptData, encoding);
  49. }
  50. public static String decode(String encryptText) throws Exception {
  51. return decode(encryptText,ENCODE_KEY,ENCODE_IV);
  52. }
  53. }