当前位置:首页 > 60秒读懂世界 > AES加密解密工具类:快速实现加解密的Java代码片段

AES加密解密工具类:快速实现加解密的Java代码片段

一叶知秋2024-08-04 14:43:3760秒读懂世界8

AES加密解密工具类:快速实现加解密的Java代码片段

随着网络安全意识的不断提高,数据加密技术在各类应用中变得尤为重要。AES(Advanced Encryption Standard)加密算法因其高安全性、快速性和易用性而被广泛应用于各种场景。本文将向您介绍一个简洁的Java代码片段,帮助您快速实现AES加密和解密功能。

一、AES加密算法简介

AES是一种对称加密算法,这意味着加密和解密使用相同的密钥。它支持128位、192位和256位密钥长度,是目前最常用的加密算法之一。

AES加密解密工具类:快速实现加解密的Java代码片段

二、Java代码实现AES加密解密

以下是一个简单的AES加密解密工具类,包含加密和解密方法,支持多种密钥长度。

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {

    /**
     * 生成AES密钥
     * @return 密钥
     * @throws Exception
     */
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // 初始化密钥长度为128位
        return keyGenerator.generateKey();
    }

    /**
     * 加密
     * @param data 待加密数据
     * @param key 密钥
     * @return 加密后的数据
     * @throws Exception
     */
    public static String encrypt(String data, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    /**
     * 解密
     * @param encryptedData 加密后的数据
     * @param key 密钥
     * @return 解密后的数据
     * @throws Exception
     */
    public static String decrypt(String encryptedData, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData);
    }

    public static void main(String[] args) throws Exception {
        // 生成AES密钥
        SecretKey key = generateKey();
        System.out.println("密钥:" + key);

        // 加密
        String data = "Hello, AES!";
        String encryptedData = encrypt(data, key);
        System.out.println("加密后的数据:" + encryptedData);

        // 解密
        String decryptedData = decrypt(encryptedData, key);
        System.out.println("解密后的数据:" + decryptedData);
    }
}

三、使用工具类

在上面的代码中,我们首先生成一个AES密钥,然后使用该密钥对数据进行加密和解密。您可以根据实际需求调整密钥长度。

四、总结

本文提供了一个简单的AES加密解密工具类,帮助您快速实现加解密功能。在实际应用中,您可能需要根据具体场景对工具类进行扩展,例如支持多种密钥长度、填充方式等。希望这篇文章对您有所帮助。

扫描二维码推送至手机访问。

版权声明:本站部分文章来自AI创作、互联网收集,请查看免责申明

本文链接:https://www.yyzq.team/post/373356.html

新工具上线:
分享给朋友: