JAVA使用AES实现对称加密

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

/**
 * @author chunyang.leng
 * @date 2021-11-05 11:18 上午
 */

public class AesUtils {

    /**
     * 密钥长度必须为16位
     */
    private static final String PASSWORD = "0123456789123456";

    private static final String ALGORITHM = "AES";
    
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    /**
     * AES加密字符串
     *
     * @param message 需要被加密的字符串
     * @return base64 密文
     */
    public static String encrypt(String message) throws Exception {
        if (message == null ){
            return null;
        }
        // AES专用密钥
        SecretKeySpec secretKey = new SecretKeySpec(PASSWORD.getBytes(), ALGORITHM);
        // 创建密码器
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        byte[] byteContent = message.getBytes(StandardCharsets.UTF_8);
        // 初始化为加密模式的密码器
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        // 加密后的byte数据
        byte[] bytes = cipher.doFinal(byteContent);
        // 转base64
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 解密AES加密过的字符串
     *
     * @param encryptMessage  AES加密过过的内容
     * @return 明文
     */
    public static String decrypt(String  encryptMessage)throws Exception {
        if (encryptMessage == null){
            return null;
        }
        
        byte[] decodeArray = Base64.getDecoder().decode(encryptMessage);
        // AES专用密钥
        SecretKeySpec secretKey = new SecretKeySpec(PASSWORD.getBytes(), ALGORITHM);
        // 创建密码器
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        // 初始化为解密模式的密码器
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        // 明文数组
        byte[] bytes = cipher.doFinal(decodeArray);

        return new String(bytes, StandardCharsets.UTF_8);

    }


    public static void main(String[] args) throws Exception {

        boolean b = true;
        for (int i = 0; i < 50 ; i++) {
            String uuid = UUID.randomUUID().toString();
            System.out.println("uuid=====>" + uuid);
            String encrypt = encrypt(uuid);
            System.out.println("encrypt=====>" + encrypt);
            String decrypt = decrypt(encrypt);
            System.out.println("decrypt=====>" + decrypt);
            b &= decrypt.equals(uuid);
        }
        System.out.println("final =====>" + b);

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北漂的菜小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值