对称加密算法AES

一、算法介绍

AES是对称加密算法,这种加密算法用来加密和解密的数据是相同的。

二、功能实现

代码实现及使用如下:

import java.nio.charset.StandardCharsets;
import java.util.Base64;

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

import org.springframework.util.StringUtils;

/**
 * AES加密算法工具类
 * @since 2023-09-14 10:50
 *
 */
public class AESUtil {

	private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
	private static final String SECRET_KEY = "5ir1k#xezi_IufR5"; // 必须是16个字符

	/**
	 * 使用默认密钥加密
	 * @param plainText 明文
	 * @return 加密后的密文
	 * @throws Exception
	 */
	public static String encrypt(String plainText) throws Exception {
	    return encrypt(plainText, null);
	}
	
	/**
     * 加密
     * @param plainText 明文
     * @param secretKey 密钥(密钥长度因为16个字符)
     * @return 加密后的密文
     * @throws Exception
     */
	public static String encrypt(String plainText, String secretKey) throws Exception {
	    if(!StringUtils.hasText(secretKey))secretKey = SECRET_KEY;
		SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
		Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] encryptedData = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
		return Base64.getEncoder().encodeToString(encryptedData);
	}

	/**
	 * 使用默认密钥解密
	 * @param encryptedData 密文
	 * @return 解密后的内容
	 * @throws Exception
	 */
	public static String decrypt(String encryptedData) throws Exception {
	    return decrypt(encryptedData, null);
	}
	
	/**
     * 解密
     * @param encryptedData 密文
     * @param secretKey 密钥(密钥长度因为16个字符)
     * @return 密文对应的明文
     * @throws Exception
     */
	public static String decrypt(String encryptedData, String secretKey) throws Exception {
	    if(!StringUtils.hasText(secretKey))secretKey = SECRET_KEY;
		SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
		Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
		return new String(decryptedData, StandardCharsets.UTF_8);
	}
	
	public static void main(String[] args) throws Exception {
        //明文
	    String planText = "hello world!";
        
	    //SECRET_KEY 默认密钥
	    //加密(默认密钥加密)
	    String encryptedData = encrypt(planText);
	    System.out.println(encryptedData);
	    
	    //解密(默认密钥解密)
	    System.out.println(decrypt(encryptedData));
    }
	
}

如果对你有用的话,记得点赞加关注😊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值