欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java AES 加解密工具类

程序员文章站 2024-03-14 14:46:46
...
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author potoyang
 * Description: AES 加解密工具类
 */
@Slf4j
class AESUtil {

    private static final String DEFAULT_CIPHER_ALGORITHM = "AES";

    @Setter
    private String content;

    private String secret;

    AESUtil(String content) {
        this.content = content;
        this.secret = "324iu23094u598ndsofhsiufhaf_+0wq-42q421jiosadiusadiasd";
    }

    /**
     * AES 加密
     */
    String encrypt() {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            Key key = getKey();
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return byte2hex(result);
        } catch (Exception e) {
            log.error("AES 加密出错: [{}]", e.getMessage());
        }
        return null;
    }

    /**
     * AES 解密
     */
    String decrypt() {
        if (content.length() < 1) {
            return null;
        }

        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            Key key = getKey();
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] original = cipher.doFinal(hex2byte(content));
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES 解密出错: [{}]", e.getMessage());
        }
        return null;
    }

    private Key getKey() {
        SecretKey key = null;
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(secret.getBytes());
            generator.init(128, random);
            key = generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return key;
    }
    
    private byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int len = strhex.length();
        if (len % 2 == 1) {
            return null;
        }
        byte[] b = new byte[len / 2];
        for (int i = 0; i != len / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
        }
        return b;
    }

    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (byte value : b) {
            stmp = (Integer.toHexString(value & 0XFF));
            if (stmp.length() == 1) {
                hs.append("0").append(stmp);
            } else {
                hs.append(stmp);
            }
        }
        return hs.toString().toUpperCase();
    }
}