DesUtils.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.caimei.util.helipay;
  2. import javax.crypto.*;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import java.io.UnsupportedEncodingException;
  5. import java.security.InvalidKeyException;
  6. import java.security.NoSuchAlgorithmException;
  7. public class DesUtils {
  8. public static final String ENCODE = "UTF-8";
  9. private DesUtils() {
  10. }
  11. public static String encode(String key, String data) throws NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
  12. try {
  13. byte[] keyByte = key.getBytes(ENCODE);
  14. byte[] dataByte = data.getBytes(ENCODE);
  15. byte[] valueByte = des3Encryption(
  16. keyByte, dataByte);
  17. String value = new String(Base64.encodeBase64(valueByte), ENCODE);
  18. return value;
  19. } catch (Exception e) {
  20. System.err.println("3des加密失败:" + e.getMessage());
  21. throw e;
  22. }
  23. }
  24. public static String decode(String key, String value) throws NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
  25. try {
  26. byte[] keyByte = key.getBytes(ENCODE);
  27. byte[] bytes = value.getBytes(ENCODE);
  28. byte[] dataByte = des3Decryption(keyByte,
  29. Base64.decode(bytes));
  30. String data = new String(dataByte, ENCODE);
  31. return data;
  32. } catch (Exception e) {
  33. System.err.println("3des解密失败:" + e.getMessage());
  34. throw e;
  35. }
  36. }
  37. private static byte[] des3Encryption(byte[] key, byte[] data) throws
  38. NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
  39. BadPaddingException, IllegalBlockSizeException, IllegalStateException {
  40. final String Algorithm = "DESede";
  41. SecretKey deskey = new SecretKeySpec(key, Algorithm);
  42. Cipher c1 = Cipher.getInstance(Algorithm);
  43. c1.init(Cipher.ENCRYPT_MODE, deskey);
  44. return c1.doFinal(data);
  45. }
  46. private static byte[] des3Decryption(byte[] key, byte[] data) throws
  47. NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
  48. BadPaddingException, IllegalBlockSizeException, IllegalStateException {
  49. final String Algorithm = "DESede";
  50. SecretKey deskey = new SecretKeySpec(key, Algorithm);
  51. Cipher c1 = Cipher.getInstance(Algorithm);
  52. c1.init(Cipher.DECRYPT_MODE, deskey);
  53. return c1.doFinal(data);
  54. }
  55. }