AesUtil.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. package com.example.xiaoshiweixinback.business.utils;
  2. import java.io.IOException;
  3. import java.security.GeneralSecurityException;
  4. import java.security.InvalidAlgorithmParameterException;
  5. import java.security.InvalidKeyException;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.util.Base64;
  8. import javax.crypto.Cipher;
  9. import javax.crypto.NoSuchPaddingException;
  10. import javax.crypto.spec.GCMParameterSpec;
  11. import javax.crypto.spec.SecretKeySpec;
  12. public class AesUtil {
  13. static final int KEY_LENGTH_BYTE = 32;
  14. static final int TAG_LENGTH_BIT = 128;
  15. private final byte[] aesKey;
  16. public AesUtil(byte[] key) {
  17. if (key.length != KEY_LENGTH_BYTE) {
  18. // throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节");
  19. }
  20. this.aesKey = key;
  21. }
  22. public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
  23. throws GeneralSecurityException, IOException {
  24. try {
  25. Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
  26. SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
  27. GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
  28. cipher.init(Cipher.DECRYPT_MODE, key, spec);
  29. cipher.updateAAD(associatedData);
  30. return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
  31. } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
  32. throw new IllegalStateException(e);
  33. } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
  34. throw new IllegalArgumentException(e);
  35. }
  36. }
  37. }