java版AES加密算法实现

项目中需要用到AES算法加密,写了个可用的工具类,做一下记录。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

    private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);

    // 默认全部使用ECB模式的对称加密(主要是因为ECB模块适合并行计算)
    private static final String ALGORITHM_PADDING = "AES/ECB/PKCS5Padding";
    private static final String ALGORITHM_NAME = "AES";
    private static KeyGenerator sKeyGen;

    static {
        try {
            sKeyGen = KeyGenerator.getInstance(ALGORITHM_NAME);
            sKeyGen.init(128);
        } catch (Exception e) {
            logger.error("AES init exception:", e);
        }
    }

    /**
     * 加密方法
     *
     * @param content
     * @param password
     * @return
     */
    private static byte[] encrypt(String content, byte[] password) {
        try {
            SecretKeySpec key = new SecretKeySpec(password, ALGORITHM_NAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM_PADDING);
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(byteContent);
        } catch (Exception e) {
            logger.error("AES encrypt exception:", e);
        }
        return null;
    }

    /**
     * 解密方法
     *
     * @param content
     * @param password
     * @return
     */
    private static byte[] decrypt(byte[] content, byte[] password) {
        try {
            SecretKeySpec key = new SecretKeySpec(password, ALGORITHM_NAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM_PADDING);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            logger.error("AES decrypt exception:", e);
        }
        return null;
    }

    /**
     * 字符串转换为二进制字节数组
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr == null || hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 二进制字节数组转换为字符串
     *
     * @param bytes
     * @return
     */
    public static String byteArray2HexString(byte[] bytes) {
        if (null == bytes) {
            return "";
        }
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String str = Integer.toHexString(0xFF & b);
            while (str.length() < 2) {
                str = "0" + str;
            }
            hexString.append(str);
        }
        return hexString.toString();
    }

    /**
     * 加密主方法
     *
     * @param content
     * @param key
     * @return
     */
    public static String encode(String content, byte[] key) {
        return byteArray2HexString(encrypt(content, key));
    }

    /**
     * 解密主方法
     *
     * @param content
     * @param key
     * @return
     */
    public static String decode(String content, byte[] key) {
        byte[] b = decrypt(parseHexStr2Byte(content), key);
        return new String(b);
    }
}

使用的时候,加密直接调用encode方法,解密的时候调用decode方法。

下面是一个简单的 Java 实现 AES 加密算法的示例代码: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { public static String encrypt(String plaintext, String key, String iv) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] encrypted = cipher.doFinal(plaintext.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } public static String decrypt(String ciphertext, String key, String iv) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] decoded = Base64.getDecoder().decode(ciphertext); byte[] decrypted = cipher.doFinal(decoded); return new String(decrypted, StandardCharsets.UTF_8); } public static void main(String[] args) throws Exception { String plaintext = "Hello, world!"; String key = "0123456789abcdef"; String iv = "fedcba9876543210"; String ciphertext = encrypt(plaintext, key, iv); System.out.println("Ciphertext: " + ciphertext); String decrypted = decrypt(ciphertext, key, iv); System.out.println("Decrypted: " + decrypted); } } ``` 注意:这只是一个简单的示例代码,实际使用中应该考虑更多的安全因素,比如密钥的生成和管理、IV 的随机性等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值