java AES加密

使用JDK8引入的 java.util.Base64 负责base64转码
Base64Tools 工具类,AES加密要用到它,负责 byte 数组的base64编码,base64 编码的目的是消除乱码

import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class Base64Tools {
    private final static Base64.Decoder decoder = Base64.getDecoder();
    private final static Base64.Encoder encoder = Base64.getEncoder();

    public static byte[] encode(byte[] content) throws UnsupportedEncodingException {
        return encoder.encode(content);
    }

    public static byte[] decode(byte[] content) throws UnsupportedEncodingException {
        return decoder.decode(content);
    }
}

AESTools 工具类,负责对 byte 数组加密和解密

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AESTools {
    private static final Base64.Decoder decoder = Base64.getDecoder();
    private static final Base64.Encoder encoder = Base64.getEncoder();
	public static byte[] AESEncode(String password, byte[] content) {
		try {
			KeyGenerator keygen = KeyGenerator.getInstance("AES");
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes());
			keygen.init(128, random);
			SecretKey originalKey = keygen.generateKey();
			SecretKey key = new SecretKeySpec(originalKey.getEncoded(), "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return Base64Tools.encode(cipher.doFinal(content)); // 加密后用base64编码
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] AESDecode(String password, byte[] content) {
		try {
			KeyGenerator keygen = KeyGenerator.getInstance("AES");
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes());
			keygen.init(128, random);
			SecretKey originalKey = keygen.generateKey();
			SecretKey key = new SecretKeySpec(originalKey.getEncoded(), "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			return cipher.doFinal(Base64Tools.decode(content));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		}
		return null;
	}

}

测试用例我从网上找了一段文字,将它加密后再解密,和原文进行对比

public class Main {
    public static void main(String[] args) throws Exception {
		String password = "passwordwhateveryouwant";
		String content = "We hold these truths to be self-evident, that all men are created equal\n我们认为下述真理是不言而喻的:人人生而平等";

		System.out.println(content);
		String encryptedString = new String(AESTools.AESEncode(password, content.getBytes()));
		System.out.println(encryptedString);
		String decryptedString = new String(AESTools.AESDecode(password, encryptedString.getBytes()));
		System.out.println(decryptedString);
		if (content.equals(decryptedString)) System.out.printf("原文和加密后再解密的结果相等");
		else System.out.printf("原文和加密后再解密的结果不相等");
    }
}

运行结果
在这里插入图片描述

### Java AES 加密实现教程 #### 创建加密工具类 为了便于管理和重复利用,建议创建一个专门用于处理AES加解密操作的工具类 `AesUtil`。 ```java import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesUtil { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; public static SecretKeySpec generateKey() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM); keyGen.init(256); // 使用256位长度秘钥 SecretKey secretKey = keyGen.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), ALGORITHM); } public static byte[] encrypt(String plainText, SecretKeySpec key, IvParameterSpec iv) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, key, iv); return cipher.doFinal(plainText.getBytes()); } public static String decrypt(byte[] cipherText, SecretKeySpec key, IvParameterSpec iv) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, key, iv); return new String(cipher.doFinal(cipherText)); } } ``` 此代码展示了如何生成AES秘钥以及执行基本的加密和解密过程[^1]。注意这里选择了更安全的CBC模式而非示例中的ECB模式,并加入了初始化向量IV来增强安全性。 对于实际应用而言,还需要考虑秘钥的安全存储方式、异常处理机制等问题,在生产环境中应遵循最佳实践指南以确保数据传输的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值