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

java 加密

作者:/神經病/   发布日期:2025-08-10   浏览:85

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[] cipherText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(cipherText));
    }

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

            // 要加密的文本
            String originalText = "Hello, World!";

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

            // 解密
            String decryptedText = decrypt(encryptedText, secretKey);
            System.out.println("Decrypted: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

解释说明:

  1. 生成密钥:使用 KeyGenerator 类来生成一个 AES 算法的密钥。这里我们生成了一个 128 位的密钥。
  2. 加密方法:通过 Cipher 类来进行加密操作,传入明文和密钥,返回加密后的字节数组。
  3. 解密方法:同样使用 Cipher 类进行解密操作,传入加密后的字节数组和密钥,返回解密后的字符串。
  4. 主函数:在 main 函数中,我们演示了如何生成密钥、加密和解密一个简单的字符串。

这个例子展示了如何使用 Java 内置的加密库(如 javax.crypto)来进行基本的加密和解密操作。

上一篇:java list 转array

下一篇:java list 交集

大家都在看

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 中文站