AES加解密字符串详解

前言:
文中代码是可以直接复制使用的,但是这里我使用到了Base64和slf4jjar包,不需要的可以自行修改.


import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

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


/**
 * AES工具类;
 *	用于对信息进行加解密的AES工具类;
 * @author MaLinQing
 *
 */
public class AESUtils {
	
	private AESUtils() {}//静态工具类,不需要new对象;
	
	private static final Logger LOGGER =  LoggerFactory.getLogger("passengerLogger"); 
	private static final String password ="gjh%^&(&  {}77";//加解密时所需的密码,内部使用可以直接写死,外部调用动态传输可以直接在形参中定义
	
	/**
	* AES加密字符串
	* 
	* @param content
	* 需要被加密的字符串
	* @return 密文
	*/
	public static String encrypt(String content) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");//构造密钥生成器,指定为AES算法,不区分大小写
		
			kgen.init(128, new SecureRandom(password.getBytes()));//根据传入的字节数组,生成一个128位的随机源
		
			SecretKey secretKey = kgen.generateKey();// 产生原始对称密钥
		
			byte[] enCodeFormat = secretKey.getEncoded();// 获得原始对称密钥的字节数组
		
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");//根据字节数组生成AES密钥
		
			Cipher cipher = Cipher.getInstance("AES");//根据指定算法AES生成密码器
		
			byte[] byteContent = content.getBytes("UTF-8"); //将报文转成字节数组
			//(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
		
			cipher.init(Cipher.ENCRYPT_MODE, key);//初始化密码器,
		
			byte[] ciphertext = cipher.doFinal(byteContent);// 加密
			
			return (Base64.encode(ciphertext));
	
		} catch (NoSuchPaddingException e) {
			LOGGER.error("生成cipher密码器异常!异常信息:{}",e);
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error("无法通过AES加密算法生成cipher异常!异常信息:{}",e);
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("byteContent-UTF-8字符转换异常!异常信息:{}",e);
		} catch (InvalidKeyException e) {
			LOGGER.error("cipher初始化失败异常!异常信息:{}",e);
		} catch (IllegalBlockSizeException e) {
			LOGGER.error("数据长度不正确导致报文加密失败!异常信息:{}",e);
		} catch (BadPaddingException e) {
			LOGGER.error("byteContent未正确转换-导致报文加密失败!异常信息:{}",e);
		}
		return null;
		}
	
	/**
     * 解密AES加密过的字符串
     * 
     * @param content
     * AES加密过过的内容
     * @return 明文
     */
    public static String decrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");//构造密钥生成器,指定为AES算法,不区分大小写
            
            kgen.init(128, new SecureRandom(password.getBytes()));//根据传入的字节数组,生成一个128位的随机源
            
            SecretKey secretKey = kgen.generateKey();//产生原始对称密钥
            
            byte[] enCodeFormat = secretKey.getEncoded();//获得原始对称密钥的字节数组
            
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");//根据字节数组生成AES密钥
            
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
            
            byte[] byteContent= Base64.decode(content);//将密文解码成字节数组
            
            byte[] byteDecode = cipher.doFinal(byteContent); //解密;
			
	    return new String(byteDecode,"UTF-8");

        } catch (NoSuchAlgorithmException e) {
        	LOGGER.error("无法通过AES加密算法生成cipher异常!异常信息:{}",e);
        } catch (NoSuchPaddingException e) {
        	LOGGER.error("生成cipher密码器异常!异常信息:{}",e);
        } catch (InvalidKeyException e) {
        	LOGGER.error("cipher初始化失败异常!异常信息:{}",e);
        } catch (IllegalBlockSizeException e) {
        	LOGGER.error("数据长度不正确导致报文加密失败!异常信息:{}",e);
        } catch (BadPaddingException e) {
        	LOGGER.error("byteContent未正确转换-导致报文加密失败!异常信息:{}",e);
        } catch (UnsupportedEncodingException e) {
        	LOGGER.error("byteDecode-UTF-8字符转换异常!异常信息:{}",e);
		}
        return null;
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值