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

java 字符串加密

作者:月冷清   发布日期:2026-01-28   浏览:78

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

public class StringEncryptionExample {

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

    // 加密字符串
    public static String encrypt(String plainText, byte[] key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密字符串
    public static String decrypt(String encryptedText, byte[] key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }

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

            // 原始字符串
            String originalString = "Hello, World!";
            System.out.println("Original: " + originalString);

            // 加密
            String encryptedString = encrypt(originalString, key);
            System.out.println("Encrypted: " + encryptedString);

            // 解密
            String decryptedString = decrypt(encryptedString, key);
            System.out.println("Decrypted: " + decryptedString);

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

解释说明

  1. 生成密钥:

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

    • 使用 Cipher 类对字符串进行加密。加密算法为 AES,加密后的字节数组使用 Base64 编码转换为字符串,以便于传输和存储。
  3. 解密字符串:

    • 使用相同的密钥和 Cipher 类对加密后的字符串进行解密。解密后的字节数组转换回原始字符串。
  4. 主函数:

    • 生成密钥,加密并打印原始字符串,然后解密并打印解密后的字符串,验证加密解密过程是否正确。

这个示例展示了如何使用 Java 的 javax.crypto 包来进行字符串的加密和解密操作。

上一篇:java 邮件发送

下一篇:java调用接口

大家都在看

java url decode

java判断是windows还是linux

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java list 查找

java 解压rar

java读取excel中的图片

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

Laravel 中文站