AES算法的对称加密工具

import java.security.Security;
import java.util.Base64;

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

import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
 * 对称加密工具类,用于对数据使用相同的密钥和向量进行加密和解密
 * 第三方包的maven依赖:
 * <dependency>
    	<groupId>bouncycastle</groupId>
    	<artifactId>bouncycastle-jce-jdk13</artifactId>
    	<version>112</version>
    	<scope>runtime</scope>
    </dependency>
 * @author 大别山人
 */
public final class AESUtil {
	private AESUtil() {throw new UnsupportedOperationException("工具类不需要实例化");}
	private static final String ALGORITHM = "AES";
	private static final String ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
	/**
	 * 使用指定密钥和向量对参数数据进行加密处理
	 * @param data	明文数据
	 * @param key	密钥
	 * @param vi	向量
	 * @return		密文数据(base64编码)
	 */
	public static final String encrypt(String data,String key,String vi) {
		try {
			
			return Base64.getEncoder().encodeToString(execute(data.getBytes(),key,vi,false));
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 使用指定密钥和向量对密文数据进行解迷处理
	 * @param data	密文数据
	 * @param key	密钥
	 * @param vi	向量
	 * @return		明文数据
	 */
	public static final String decrypt(String data,String key,String vi) {
		try {
			return new String(execute(Base64.getDecoder().decode(data.getBytes()),key,vi,true));
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	private static final byte[] execute(byte[] data,String key,String vi,boolean isDecrypt) throws Exception {
		Security.addProvider(new BouncyCastleProvider());
		SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
		IvParameterSpec ips = new IvParameterSpec(vi.getBytes());
		Cipher cipher = Cipher.getInstance(ALGORITHM_CBC,"BC");
		cipher.init(isDecrypt?Cipher.DECRYPT_MODE:Cipher.ENCRYPT_MODE, keySpec, ips);
		return cipher.doFinal(data);
	}
	public static void main(String[] args) {
		String key = "12345678901234561234567890123456";
		String vi = "1234567890123456";
		String data = "bai日依山尽,黄河入海流。123!@#!@#<>?,./";
		String encrypt = encrypt(data, key, vi);
		System.out.println(encrypt);
		System.out.println(decrypt(encrypt, key, vi));
	}
}

  

posted on 2020-05-21 00:21  大别山人  阅读(337)  评论(0编辑  收藏  举报