Java AES

文章详细介绍了如何在Java中使用AES(高级加密标准)进行字符串的加密和解密操作,包括基本模式(ECB)和CBC模式,以及AESUtil类的使用方法和示例。
摘要由CSDN通过智能技术生成
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtil {

    /**
     * 编码
     */
    private static final String ENCODING = "UTF-8";

    /**
     * 算法定义
     */
    private static final String AES_ALGORITHM = "AES";

    /**
     * 指定填充方式
     */
    private static final String CIPHER_PADDING = "AES/ECB/PKCS5Padding";
    private static final String CIPHER_CBC_PADDING = "AES/CBC/PKCS5Padding";

    /**
     * 偏移量(CBC中使用,增强加密算法强度)
     */
//    private static final String IV_SEED = "1234567812345678";

    /**
     * 加密
     *
     * @param content 内容
     * @param aesKey  密钥
     * @return 数据
     */
    public static String encrypt(String content, String aesKey) throws Exception {
        if ((content == null || content.trim().isEmpty()) || (aesKey == null || aesKey.trim().length() != 16)) {
            throw new Exception("内容或密码不符合规范");
        }
        System.out.println("content:" + content + "\taesKey:" + aesKey);
        //密钥
        byte[] bytes = aesKey.getBytes();
        //设置加密算法,生成密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
        //算法模式:补码
        Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
        //选择加密
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        //根据待加密内容生成字节数组
        byte[] contentBytes = cipher.doFinal(content.getBytes(ENCODING));
        //base64转码
        return Base64.getEncoder().encodeToString(contentBytes);
    }

    public static String decrypt(String content, String aesKey) throws Exception {
        if ((content == null || content.trim().isEmpty()) || (aesKey == null || aesKey.trim().length() != 16)) {
            throw new Exception("内容或密码不符合规范");
        }
        System.out.println("content:" + content + "\taesKey:" + aesKey);
        //密钥
        byte[] bytes = aesKey.getBytes();
        //设置加密算法,生成密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
        //算法模式:补码
        Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
        //选择解密模式
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        //先解密base64,后ase
        byte[] decode = Base64.getDecoder().decode(content);
        return new String(cipher.doFinal(decode), ENCODING);
    }

    /**
     * AES_CBC加密
     *
     * @param content 待加密内容
     * @param aesKey  密码
     * @return 密文
     */
    public static String encryptCBC(String content, String aesKey) throws Exception {
        if ((content == null || content.trim().isEmpty()) || (aesKey == null || aesKey.trim().length() != 16)) {
            throw new Exception("内容或密码不符合规范");
        }
        System.out.println("content:" + content + "\taesKey:" + aesKey);
        //对密码进行编码
        byte[] bytes = aesKey.getBytes(ENCODING);
        //设置加密算法,生成秘钥
        SecretKeySpec keySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
        // "算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance(CIPHER_CBC_PADDING);
        //偏移
        // 根据随机数生成IV
        byte[] bytesIV = new byte[16];
        new SecureRandom().nextBytes(bytesIV);
        IvParameterSpec iv = new IvParameterSpec(bytesIV);
        //选择加密
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        //根据待加密内容生成字节数组
        byte[] encrypted = cipher.doFinal(content.getBytes(ENCODING));
        //返回base64字符串
        return Base64.getEncoder().encodeToString(bytesIV) + "@" + Base64.getEncoder().encodeToString(encrypted);

    }

    /**
     * AES_CBC解密
     *
     * @param content 待解密内容
     * @param aesKey  密码
     * @return 原文
     */
    public static String decryptCBC(String content, String aesKey) throws Exception {
        if ((content == null || content.trim().isEmpty() || !content.contains("@")) || (aesKey == null || aesKey.trim().length() != 16)) {
            throw new Exception("内容或密码不符合规范");
        }
        System.out.println("content:" + content + "\taesKey:" + aesKey);

        String[] contentArray = content.split("@");
        String base64Iv = contentArray[0];
        String base64Content = contentArray[1];
        Base64.Decoder decoder = Base64.getDecoder();

        //对密码进行编码
        byte[] bytes = aesKey.getBytes(ENCODING);
        //设置解密算法,生成秘钥
        SecretKeySpec keySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
        //偏移
        IvParameterSpec iv = new IvParameterSpec(decoder.decode(base64Iv));
        // "算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance(CIPHER_CBC_PADDING);
        //选择解密
        cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

        //先进行Base64解码
        byte[] decodeBase64 = decoder.decode(base64Content);

        //根据待解密内容进行解密
        byte[] decrypted = cipher.doFinal(decodeBase64);
        //将字节数组转成字符串
        return new String(decrypted, ENCODING);

    }


    public static void main(String[] args) throws Exception {
        String aesKey = "key";
        System.out.println("=============普通模式");
        String content = "admin";
        String encrypt = AESUtil.encrypt(content, aesKey);
        System.out.println(encrypt);
        String decrypt = AESUtil.decrypt(encrypt, aesKey);
        System.out.println(decrypt);
        System.out.println("=============cbc模式");
        String encryptCBC = AESUtil.encryptCBC(content, aesKey);
        System.out.println(encryptCBC);
        String decryptCBC = AESUtil.decryptCBC(encryptCBC, aesKey);
        System.out.println(decryptCBC);
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值