目录

Java 中 AES 的使用

目录

下面编写一个 AES 的工具类。

import lombok.extern.slf4j.Slf4j;
import net.wwpjw.backend.common.StatusEnum;
import net.wwpjw.backend.exception.SecurityException;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES 加密工具包.
 * @author yuhanliu
 */
@Component
@Slf4j
public class AesUtil {

  /**
   * AES 加密.
   * @param content 内容
   * @param secret 秘密
   * @return String Base64加密后
   */
  public String encrypt(String content, String secret) {
    try {
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, getKey(secret));
      return Base64.getEncoder().encodeToString(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
      log.error("AES加密失败:" + e.getLocalizedMessage());
      throw new SecurityException(StatusEnum.AES_ENCRYPT_FAILURE, e.getLocalizedMessage());
    }
  }

  /**
   * AES 解密.
   * @param encrypt 加密密文.
   * @param secret 密钥.
   * @return String
   */
  public String decrypt(String encrypt, String secret) {
    try {
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.DECRYPT_MODE, getKey(secret));
      return new String(cipher.doFinal(Base64.getDecoder().decode(encrypt)));
    } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
      log.error("AES解密失败:" + e.getLocalizedMessage());
      throw new SecurityException(StatusEnum.AES_DECRPYT_FAILURE, e.getLocalizedMessage());
    }
  }

  private SecretKey getKey(String secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    MessageDigest sha = null;
    byte[] key = secret.getBytes(StandardCharsets.UTF_8);
    sha = MessageDigest.getInstance("SHA-1");
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16);
    return new SecretKeySpec(key, "AES");
  }
}

测试结果通过,例如”AES“、”你好“,特别长的内容也都可以完成。

主要内容参考了[1],在我查找资料的时候,发现中文博客例如 CSDN、简书近年来的文章都是很没有水平的,又老又旧、抄来抄去。


[1] Java AES Encryption Decryption Example