AesUtils.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. return null;
  24. }
  25. }
  26. public static String decrypt(String content, String key) throws Exception {
  27. try {
  28. byte[] decoded = Base64.decodeBase64(content);
  29. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  30. SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
  31. IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
  32. cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
  33. byte[] original = cipher.doFinal(decoded);
  34. int i = original.length - 1;
  35. for (; i >= 0; i--) {
  36. if (original[i] != 0) {
  37. break;
  38. }
  39. }
  40. byte[] subarray = new byte[i + 1];
  41. System.arraycopy(original, 0, subarray, 0, i + 1);
  42. return new String(subarray);
  43. } catch (Exception e) {
  44. return null;
  45. }
  46. }
  47. }