Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

aes加密 java

作者:炼狱死神   发布日期:2025-08-12   浏览:59

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

public class AESExample {

    // 生成AES密钥
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // 可以选择128, 192或256位密钥长度
        return keyGen.generateKey();
    }

    // 加密方法
    public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密方法
    public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) {
        try {
            // 生成密钥
            SecretKey secretKey = generateKey();

            // 要加密的明文
            String plainText = "Hello, AES Encryption!";

            // 加密
            String encryptedText = encrypt(plainText, secretKey);
            System.out.println("Encrypted: " + encryptedText);

            // 解密
            String decryptedText = decrypt(encryptedText, secretKey);
            System.out.println("Decrypted: " + decryptedText);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

解释说明

  1. 生成AES密钥:

    • 使用 KeyGenerator 类生成一个AES密钥。可以选择128、192或256位的密钥长度。
  2. 加密方法:

    • 使用 Cipher 类进行加密操作。首先初始化 Cipher 对象为加密模式,并传入生成的密钥。然后将明文转换为字节数组并进行加密,最后将加密后的字节数组用Base64编码成字符串返回。
  3. 解密方法:

    • 同样使用 Cipher 类进行解密操作。初始化 Cipher 对象为解密模式,并传入相同的密钥。将Base64编码的加密字符串解码为字节数组后进行解密,最后将解密后的字节数组转换为字符串返回。
  4. 主程序:

    • 生成密钥,对明文进行加密和解密,并输出结果。

这个示例展示了如何在Java中使用AES算法进行加密和解密操作。

上一篇:java实现aes的五种加密模式

下一篇:java判断字符串是否为纯数字

大家都在看

java连接数据库的代码

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java实体类转json字符串

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站