Java 中 AES 的使用

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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

updatedupdated2020-07-142020-07-14
加载评论