AesUtils.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.goafanti.common.utils;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.spec.IvParameterSpec;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import org.apache.commons.codec.binary.Base64;
  6. public class AesUtils {
  7. public static String encrypt(String content, String key) throws Exception {
  8. try {
  9. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  10. int blockSize = cipher.getBlockSize();
  11. byte[] dataBytes = content.getBytes();
  12. int plaintextLength = dataBytes.length;
  13. if (plaintextLength % blockSize != 0) {
  14. plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
  15. }
  16. byte[] plaintext = new byte[plaintextLength];
  17. System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
  18. SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
  19. IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
  20. cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
  21. return Base64.encodeBase64String(cipher.doFinal(plaintext));
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. return null;
  25. }
  26. }
  27. public static String decrypt(String content, String key) throws Exception {
  28. try {
  29. byte[] decoded = Base64.decodeBase64(content);
  30. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  31. SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
  32. IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
  33. cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
  34. byte[] original = cipher.doFinal(decoded);
  35. int i = original.length - 1;
  36. for (; i >= 0; i--) {
  37. if (original[i] != 0) {
  38. break;
  39. }
  40. }
  41. byte[] subarray = new byte[i + 1];
  42. System.arraycopy(original, 0, subarray, 0, i + 1);
  43. return new String(subarray);
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. return null;
  47. }
  48. }
  49. }