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

java 加解密

作者:刃起风啸凌   发布日期:2026-07-16   浏览:89

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

public class AESUtil {

    private static final String ALGORITHM = "AES";

    // 生成密钥
    public static String generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(128); // 可以选择192或256位,但需要额外的JCE支持
        SecretKey secretKey = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    // 加密
    public static String encrypt(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedData = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密
    public static String decrypt(String encryptedData, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData, "UTF-8");
    }

    public static void main(String[] args) {
        try {
            // 生成密钥
            String key = generateKey();
            System.out.println("Generated Key: " + key);

            // 原始数据
            String originalData = "Hello, World!";
            System.out.println("Original Data: " + originalData);

            // 加密数据
            String encryptedData = encrypt(originalData, key);
            System.out.println("Encrypted Data: " + encryptedData);

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

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

解释说明:

  1. 生成密钥:使用 KeyGenerator 类生成一个 AES 密钥,并将其编码为 Base64 字符串。
  2. 加密:使用 Cipher 类进行加密操作。将输入的字符串转换为字节数组,使用 AES 算法和提供的密钥进行加密,最后将加密后的字节数组编码为 Base64 字符串返回。
  3. 解密:使用 Cipher 类进行解密操作。将 Base64 编码的加密字符串解码为字节数组,使用 AES 算法和提供的密钥进行解密,最后将解密后的字节数组转换为字符串返回。
  4. 主函数:演示了如何生成密钥、加密和解密数据。

上一篇:java timeunit

下一篇:java string 转对象

大家都在看

java url decode

java判断是windows还是linux

java原始数据类型

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java常用的设计模式有哪些

java list 查找

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

Laravel 中文站