AES 加密工具类

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 *  AES 加解密工具类
 */
public class AESUtils {
    private static String KEY = "1234567890ABCDEF";

    private static String OFFSET = "1234567890ABCDEF";

    /**
     * ECB 电码本模式加密
     * @param content 待加密内容
     * @param key 秘钥
     */
    public static String aesECBEncrypt(String content, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        return Base64.encodeBase64String(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * ECB 电码本模式解密
     * @param content 待解密内容
     * @param key 秘钥
     */
    public static String aesECBDecrypt(String content, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        return new String(cipher.doFinal(Base64.decodeBase64(content)), StandardCharsets.UTF_8);
    }

    /**
     * CBC 密码分组链接模式加密,需要一个向量iv,可增加加密算法的强度
     * @param content 待加密内容
     * @param key 秘钥
     * @param offset 偏移量字符串
     */
    public static String aesCBCEncrypt(String content, String key,String offset) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(offset.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
        byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * CBC 密码分组链接模式解密
     * @param content 待解密内容
     * @param key 秘钥
     * @param offset 偏移量字符串
     */
    public static String aesCBCDecrypt(String content, String key,String offset) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(offset.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
        byte[] encrypted = cipher.doFinal(Base64.decodeBase64(content));
        return new String(encrypted, StandardCharsets.UTF_8);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值