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

java加密算法

作者:此甥孓狠善良   发布日期:2025-10-17   浏览:73

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

public class JavaEncryptionExample {

    // 生成密钥
    public static SecretKey generateKey(int n) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(n);
        SecretKey secretKey = keyGen.generateKey();
        return secretKey;
    }

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

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

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

            // 要加密的文本
            String originalText = "Hello, World!";
            System.out.println("Original Text: " + originalText);

            // 加密
            byte[] encryptedText = encrypt(originalText, secretKey);
            System.out.println("Encrypted Text: " + Base64.getEncoder().encodeToString(encryptedText));

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

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

解释说明:

  1. 生成密钥

    • 使用 KeyGenerator 类生成一个 AES 密钥。generateKey(int n) 方法用于生成指定长度(如128位)的密钥。
  2. 加密方法

    • 使用 Cipher 类进行加密操作。encrypt(String plainText, SecretKey secretKey) 方法接收明文和密钥,返回加密后的字节数组。
  3. 解密方法

    • 使用 Cipher 类进行解密操作。decrypt(byte[] encryptedText, SecretKey secretKey) 方法接收加密后的字节数组和密钥,返回解密后的字符串。
  4. 主函数

    • main 函数中,首先生成一个128位的 AES 密钥,然后对一段文本进行加密并打印出加密后的结果。接着对加密后的数据进行解密,并打印出解密后的文本。

通过这段代码,你可以了解如何在 Java 中使用 AES 算法进行加密和解密操作。

上一篇:java event

下一篇:java解析json格式的文件

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

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

Laravel 中文站