欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA AES对称加密解密

程序员文章站 2024-03-14 17:09:43
...
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.SecureRandom;

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

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

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * AES对称加密和解密
 * 
 * @ClassName AESUtil
 * @Description AESUtil
 * @Company 
 * @author 
 * @date 2020-7-7 下午06:21:14
 * @version 1.0
 */
public class AESUtil {

	/** 字符集编码 */
	private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");

	/** SLF4J日志 */
	private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

	/**
	 * 静态工具类禁止使用new关键字进行实例化
	 */
	private AESUtil() {
		throw new IllegalStateException("AESUtils class");
	}

	private static final String KEY = "wvfoaba0cq3d2k2e";

	/**
	 * 加密 1.构造**生成器 2.根据ecnodeRules规则初始化**生成器 3.产生** 4.创建和初始化密码器 5.内容加密 6.返回字符串
	 * 
	 * @param content
	 * @return
	 */
	public static String encode(String content) {
		try {
			KeyGenerator generator = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(KEY.getBytes());
			generator.init(128, secureRandom);
			SecretKey originalKey = generator.generateKey();
			byte[] raw = originalKey.getEncoded();
			SecretKey key = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] byteEncode = content.getBytes(CHARSET_UTF8);
			byte[] byteAES = cipher.doFinal(byteEncode);
			return new BASE64Encoder().encode(byteAES);
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("加密失败:", e);
			}
		}
		return null;
	}

	/**
	 * 解密 解密过程: 1.同加密1-4步 2.将加密后的字符串反纺成byte[]数组 3.将加密内容解密
	 * 
	 * @param content
	 * @return
	 */
	public static String decode(String content) {
		try {
			KeyGenerator generator = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(KEY.getBytes());
			generator.init(128, secureRandom);
			SecretKey originalKey = generator.generateKey();
			byte[] raw = originalKey.getEncoded();
			SecretKey key = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] byteContent = new BASE64Decoder().decodeBuffer(content);
			byte[] byteDecode = cipher.doFinal(byteContent);
			return new String(byteDecode, CHARSET_UTF8);
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("解密失败:", e);
			}
		}
		return null;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		String content = "{\"aac002\":\"32146578971315413\"}";
		String encode = AESUtil.encode(content);
		System.out.println("加密后的密文是:" + encode);
		System.out.println("解密后的明文是:" + AESUtil.decode(encode));
	}

}

此工具实现的AES加密解密可解决window和linux下加密结果不一致导致解密失败的问题

相关标签: java