AesUtil.java 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package com.fdkankan.common.util;
  2. import com.aliyuncs.utils.Base64Helper;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.SecretKeySpec;
  6. public class AesUtil {
  7. /**
  8. * @author miracle.qu
  9. * AES算法加密明文
  10. * @param data 明文
  11. * @param key 密钥,长度16
  12. * @param iv 偏移量,长度16
  13. * @return 密文
  14. */
  15. public static String encryptAES(String data,String key,String iv) throws Exception {
  16. try {
  17. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  18. int blockSize = cipher.getBlockSize();
  19. byte[] dataBytes = data.getBytes();
  20. int plaintextLength = dataBytes.length;
  21. if (plaintextLength % blockSize != 0) {
  22. plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
  23. }
  24. byte[] plaintext = new byte[plaintextLength];
  25. System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
  26. SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
  27. IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
  28. cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
  29. byte[] encrypted = cipher.doFinal(plaintext);
  30. return Base64Helper.encode(encrypted).trim();
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. return null;
  34. }
  35. }
  36. }