Java案例如何实现解密展示?

wen java案例 77

本文目录导读:

Java案例如何实现解密展示?

  1. 对称加密解密 (AES)
  2. 安全密钥管理方案
  3. 解密展示UI界面 (JavaFX)
  4. Web应用解密展示 (Spring Boot)
  5. 安全最佳实践
  6. 注意事项

我将为您介绍如何在Java中实现解密展示功能,这里提供几个常见场景的实现方案:

对称加密解密 (AES)

基本实现

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESDecryptExample {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    /**
     * AES解密
     * @param encryptedData 加密后的数据(Base64编码)
     * @param secretKey 密钥(16/24/32位)
     * @return 解密后的明文
     */
    public static String decrypt(String encryptedData, String secretKey) throws Exception {
        // 1. 创建密钥规范
        SecretKeySpec keySpec = new SecretKeySpec(
            secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        // 2. 创建密码器
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        // 3. 执行解密
        byte[] decryptedBytes = cipher.doFinal(
            Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
    // 使用示例
    public static void main(String[] args) {
        try {
            String encryptedText = "加密后的Base64字符串";
            String key = "YourSecretKey123"; // 16位密钥
            String decryptedText = decrypt(encryptedText, key);
            System.out.println("解密结果: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

安全密钥管理方案

使用密钥文件

import java.io.*;
import java.nio.file.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class SecureKeyManager {
    private static final String KEY_FILE = "secret.key";
    // 生成并保存密钥
    public static void generateAndSaveKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256); // 256位密钥
        SecretKey secretKey = keyGen.generateKey();
        // 保存到文件
        try (FileOutputStream fos = new FileOutputStream(KEY_FILE)) {
            fos.write(secretKey.getEncoded());
        }
    }
    // 从文件加载密钥
    public static SecretKey loadKey() throws Exception {
        byte[] keyBytes = Files.readAllBytes(Paths.get(KEY_FILE));
        return new SecretKeySpec(keyBytes, "AES");
    }
}

解密展示UI界面 (JavaFX)

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class DecryptDisplayApp extends Application {
    private TextArea inputArea;
    private TextArea outputArea;
    private PasswordField keyField;
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("解密展示工具");
        // 创建UI组件
        inputArea = new TextArea();
        inputArea.setPromptText("输入加密内容...");
        outputArea = new TextArea();
        outputArea.setEditable(false);
        outputArea.setPromptText("解密结果将显示在此处...");
        keyField = new PasswordField();
        keyField.setPromptText("输入密钥");
        Button decryptBtn = new Button("解密");
        decryptBtn.setOnAction(e -> decryptAndShow());
        Button clearBtn = new Button("清空");
        clearBtn.setOnAction(e -> clearAll());
        // 布局
        VBox root = new VBox(10);
        root.setPadding(new Insets(20));
        root.getChildren().addAll(
            new Label("加密内容:"),
            inputArea,
            new Label("密钥:"),
            keyField,
            new HBox(10, decryptBtn, clearBtn),
            new Label("解密结果:"),
            outputArea
        );
        Scene scene = new Scene(root, 600, 500);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    private void decryptAndShow() {
        try {
            String encrypted = inputArea.getText();
            String key = keyField.getText();
            if (encrypted.isEmpty() || key.isEmpty()) {
                showAlert("错误", "请输入加密内容和密钥");
                return;
            }
            String decrypted = AESDecryptExample.decrypt(encrypted, key);
            outputArea.setText(decrypted);
        } catch (Exception ex) {
            showAlert("解密失败", ex.getMessage());
        }
    }
    private void clearAll() {
        inputArea.clear();
        outputArea.clear();
        keyField.clear();
    }
    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setContentText(message);
        alert.showAndWait();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

Web应用解密展示 (Spring Boot)

import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@Controller
public class DecryptController {
    @GetMapping("/decrypt")
    public String showDecryptPage() {
        return "decrypt";
    }
    @PostMapping("/decrypt")
    public String decryptData(
            @RequestParam("encryptedData") String encryptedData,
            @RequestParam("key") String key,
            Model model) {
        try {
            String decrypted = AESDecryptExample.decrypt(encryptedData, key);
            model.addAttribute("result", decrypted);
            model.addAttribute("success", true);
        } catch (Exception e) {
            model.addAttribute("error", "解密失败: " + e.getMessage());
            model.addAttribute("success", false);
        }
        return "decrypt";
    }
}

HTML模板 (Thymeleaf):

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>解密展示</title>
</head>
<body>
    <h2>数据解密</h2>
    <form action="/decrypt" method="post">
        <label>加密数据:</label><br>
        <textarea name="encryptedData" rows="5" cols="50"></textarea><br><br>
        <label>密钥:</label><br>
        <input type="password" name="key" size="50"><br><br>
        <button type="submit">解密</button>
    </form>
    <div th:if="${success}">
        <h3>解密结果:</h3>
        <textarea rows="5" cols="50" th:text="${result}"></textarea>
    </div>
    <div th:if="${error}" style="color: red;">
        <p th:text="${error}"></p>
    </div>
</body>
</html>

安全最佳实践

// 1. 使用安全随机数生成初始化向量(IV)
public class SecureDecryptor {
    public static String decryptWithIV(
            String encryptedData, 
            String key, 
            byte[] iv) throws Exception {
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        SecretKeySpec keySpec = new SecretKeySpec(
            key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decrypted = cipher.doFinal(
            Base64.getDecoder().decode(encryptedData));
        return new String(decrypted, StandardCharsets.UTF_8);
    }
    // 2. 密钥派生
    public static SecretKey deriveKey(String password, byte[] salt) 
            throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(
            password.toCharArray(), 
            salt, 
            65536,  // 迭代次数
            256);   // 密钥长度
        return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    }
}

注意事项

  1. 密钥管理:密钥应安全存储,避免硬编码在代码中
  2. 算法选择:推荐使用AES-GCM模式,提供认证加密
  3. 错误处理:解密失败时不要泄露具体原因
  4. 输入验证:对解密数据进行验证,防止注入攻击
  5. 日志记录:不要在日志中记录敏感信息

根据您的具体需求选择适合的实现方案,如果需要在移动端或分布式系统中使用,建议使用HTTPS传输加密数据,并在服务端进行解密处理。

抱歉,评论功能暂时关闭!