JAVA----AES方式加密

本文详细介绍了如何使用AES加密和解密方法,包括AESUtils类中的关键函数,如加密、解密操作以及字节转换,展示了如何在Java中利用AES算法进行安全数据传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AES方式加密

封装工具方法

public class AESUtils {

	public static String AESEncrypt(String aesKey, String data) throws Exception {
		return byte2HexString(encrypt(aesKey.getBytes("utf-8"), data.getBytes("utf-8")));
	}

	public static final String AESDecrypt(String key, String data) throws Exception {
		return new String(decrypt(key.getBytes("utf-8"), hexString2Byte(data)), "utf-8");
	}

	private static byte[] decrypt(byte[] key, byte[] data) throws Exception {
		byte[] buff = get128Key(key);
		SecretKeySpec skeySpec = new SecretKeySpec(buff, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
		cipher.init(2, skeySpec, iv);
		return cipher.doFinal(data);
	}

	private static byte[] hexString2Byte(String str) {
		int len = str.length();
		String stmp = null;
		byte[] bt = new byte[len / 2];

		for (int n = 0; n < len / 2; ++n) {
			stmp = str.substring(n * 2, n * 2 + 2);
			bt[n] = (byte) Integer.parseInt(stmp, 16);
		}

		return bt;
	}

	private static byte[] encrypt(byte[] key, byte[] data) throws Exception {
		byte[] buff = get128Key(key);
		SecretKeySpec skeySpec = new SecretKeySpec(buff, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
		cipher.init(1, skeySpec, iv);
		return cipher.doFinal(data);
	}

	private static byte[] get128Key(byte[] key) {
		byte[] buff = new byte[16];
		for (int i = 0; i < 16; ++i) {
			buff[i] = 0;
		}
		if (key.length < 16) {
			System.arraycopy(key, 0, buff, 0, key.length);
		} else if (key.length > 16) {
			System.arraycopy(key, 0, buff, 0, buff.length);
		} else {
			System.arraycopy(key, 0, buff, 0, buff.length);
		}
		return buff;
	}

	private static String byte2HexString(byte[] b) {
		String hs = "";
		String stmp = "";

		for (int n = 0; n < b.length; ++n) {
			stmp = Integer.toHexString(b[n] & 255);
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}

			if (n < b.length - 1) {
				hs = hs + "";
			}
		}

		return hs.toUpperCase();
	}


//	public static void main(String[] args) throws Exception {
//		String key = "test";
//		String data = AESEncrypt(key, "123456");
//		System.out.println(data);
//		System.out.println(AESDecrypt(key, data));
//	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值