b403d66e2e1072f4fdc71297d429e089066d36a7.svn-base 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package cn.com.goldenwater.dcproj.utils;
  2. import org.apache.commons.codec.binary.Base64;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.SecretKeySpec;
  6. public class aesUtil {
  7. public static final String KEY = "jinshui@12345678";
  8. public static final String IV = "jinshui@12345678";
  9. /**
  10. * 加密方法
  11. *
  12. * @param data 要加密的数据
  13. * @return 加密的结果
  14. */
  15. public static String encrypt(String data) {
  16. try {
  17. //"算法/模式/补码方式"NoPadding PkcsPadding
  18. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  19. int blockSize = cipher.getBlockSize();
  20. byte[] dataBytes = data.getBytes();
  21. int plaintextLength = dataBytes.length;
  22. if (plaintextLength % blockSize != 0) {
  23. plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
  24. }
  25. byte[] plaintext = new byte[plaintextLength];
  26. System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
  27. SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(), "AES");
  28. IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
  29. cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
  30. byte[] encrypted = cipher.doFinal(plaintext);
  31. return new Base64().encodeToString(encrypted);
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. return null;
  35. }
  36. }
  37. /**
  38. * 解密方法
  39. *
  40. * @param data 要解密的数据
  41. * @return 解密的结果
  42. */
  43. public static String desEncrypt(String data) {
  44. try {
  45. byte[] encrypted1 = new Base64().decode(data);
  46. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  47. SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES");
  48. IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes());
  49. cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
  50. byte[] original = cipher.doFinal(encrypted1);
  51. return new String(original).trim();
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. return null;
  55. }
  56. }
  57. public static void main(String[] args) {
  58. String str = aesUtil.encrypt("Lhc_123456");
  59. System.out.println(str);
  60. System.out.println(aesUtil.desEncrypt(str));
  61. String str1 = "DwryHl zhe DEqYJHj BiIsg==";
  62. String str2 = str1.replace(" ","+");
  63. System.out.println(str2);
  64. }
  65. }