Skip to content

ASE加密工具类

java
/**
 * AES 加解密
 *
 * @author Gnerv LiGen
 */
public class AesEncryptTools {

    /**
     * 算法
     */
    private static final String STATUS_MODE = "AES";

    /**
     * 默认密钥 32字节 必须为16字节、24字节或32字节
     */
    private static final String KEY = "AE241F62C5F84F84A6CE7A305FC78151";
    private static final byte[] KEYS = KEY.getBytes(StandardCharsets.UTF_8);
    private static final GCMParameterSpec CIPHER = new GCMParameterSpec(128, KEYS);

    /**
     * "算法/模式/补码方式"
     */
    private static final String TRANS_FORMATION = "AES/GCM/NoPadding";

    private AesEncryptTools() {
    }

    public static String encrypt(String content) {
        return encrypt(content, KEYS);
    }

    public static String encrypt(String content, byte[] keys) {
        SecretKey secretKey = new SecretKeySpec(keys, STATUS_MODE);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(TRANS_FORMATION);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException("");
        }
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, CIPHER);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        }
        try {
            return Base64.getEncoder().encodeToString(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String decrypt(String content) {
        return decrypt(content, KEYS);
    }

    public static String decrypt(String content, byte[] keys) {
        // 将密文转换为16字节的字节数组
        byte[] contentBytes = Base64.getDecoder().decode(content);
        SecretKey secretKey = new SecretKeySpec(keys, STATUS_MODE);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(TRANS_FORMATION);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException(e);
        }
        try {
            cipher.init(Cipher.DECRYPT_MODE, secretKey, CIPHER);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        }
        try {
            return new String(cipher.doFinal(contentBytes), StandardCharsets.UTF_8);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }
}

Released under the MIT License.