29.Java中常见加解密算法的基本实现

java 实现常见加解密算法

1. 创建 Maven 项目

2. 项目结构

创建后的项目结构如下:

3. 添加依赖

这里主要使用 Java 内置的加密库,pom.xml不需要添加额外依赖

4. 实现常见加解密算法

修改 src/main/java/com/example/App.java 文件,实现多种加解密算法:

java 复制代码
package org.example;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

import static java.util.Base64.*;

public class App {

    public static void main(String[] args) throws Exception {
        String originalText = "这是一段需要加密的文本";

        System.out.println("原始文本: " + originalText);
        System.out.println("----------------------------------");

        // 1. AES 对称加密
        String aesEncrypted = aesEncrypt(originalText, "1234567890123456");
        System.out.println("AES加密后: " + aesEncrypted);
        System.out.println("AES解密后: " + aesDecrypt(aesEncrypted, "1234567890123456"));
        System.out.println("----------------------------------");

        // 2. DES 对称加密
        String desEncrypted = desEncrypt(originalText, "12345678");
        System.out.println("DES加密后: " + desEncrypted);
        System.out.println("DES解密后: " + desDecrypt(desEncrypted, "12345678"));
        System.out.println("----------------------------------");

        // 3. RSA 非对称加密
        KeyPair keyPair = generateRSAKeyPair();
        String rsaEncrypted = rsaEncrypt(originalText, keyPair.getPublic());
        System.out.println("RSA加密后: " + rsaEncrypted);
        System.out.println("RSA解密后: " + rsaDecrypt(rsaEncrypted, keyPair.getPrivate()));
        System.out.println("----------------------------------");

        // 4. MD5 哈希 (不可逆)
        String md5Hash = md5Hash(originalText);
        System.out.println("MD5哈希: " + md5Hash);
        System.out.println("----------------------------------");

        // 5. SHA-256 哈希 (不可逆)
        String sha256Hash = sha256Hash(originalText);
        System.out.println("SHA-256哈希: " + sha256Hash);
    }

    // AES 加密
    public static String aesEncrypt(String data, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return getEncoder().encodeToString(encryptedBytes);
    }

    // AES 解密
    public static String aesDecrypt(String encryptedData, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedBytes = getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    // DES 加密
    public static String desEncrypt(String data, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DES");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return getEncoder().encodeToString(encryptedBytes);
    }

    // DES 解密
    public static String desDecrypt(String encryptedData, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DES");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedBytes = getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    // 生成RSA密钥对
    public static KeyPair generateRSAKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 密钥长度
        return keyPairGenerator.generateKeyPair();
    }

    // RSA 加密
    public static String rsaEncrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return getEncoder().encodeToString(encryptedBytes);
    }

    // RSA 解密
    public static String rsaDecrypt(String encryptedData, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decodedBytes = getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    // MD5 哈希
    public static String md5Hash(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashBytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(hashBytes);
    }

    // SHA-256 哈希
    public static String sha256Hash(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(hashBytes);
    }

    // 字节数组转十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

5. 运行项目

编译并运行项目:

6. 加解密算法说明

对称加密算法

  1. AES (Advanced Encryption Standard)

    • 密钥长度:128、192或256位(示例中使用16字节=128位)
    • 安全高效,推荐使用
  2. DES (Data Encryption Standard)

    • 密钥长度:56位(示例中使用8字节,其中每位实际有效)
    • 已被认为不够安全,不建议在新系统中使用

非对称加密算法

  1. RSA
    • 使用公钥加密,私钥解密
    • 适用于少量数据加密或密钥交换
    • 示例中生成2048位密钥对

哈希算法(不可逆)

  1. MD5

    • 生成128位哈希值
    • 已被认为不够安全,不应用于密码存储
  2. SHA-256

    • 生成256位哈希值
    • 比MD5更安全,推荐使用

7. 注意事项

  1. 密钥管理:实际应用中,密钥需要安全存储,不能硬编码在代码中
  2. 加密模式:示例中使用默认模式,实际应用可能需要指定模式(如AES/CBC/PKCS5Padding)
  3. 异常处理:示例中简化了异常处理,实际应用需要更完善的错误处理
  4. 性能考虑:非对称加密(如RSA)比对称加密慢,通常用于加密对称密钥
  5. 盐值:哈希时建议使用盐值防止彩虹表攻击

8. 扩展建议

  1. 对于密码存储,建议使用加盐的哈希算法如PBKDF2、bcrypt或scrypt
  2. 考虑使用更现代的加密库如Google Tink或Bouncy Castle
  3. 对于大量数据加密,考虑使用对称加密加密数据,非对称加密加密对称密钥
相关推荐
captain3762 分钟前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis
呆呆虫1212 分钟前
用 orjson 加速 SerpBase 响应解析:基准对比与注意事项
开发语言·php
2601_9707038323 分钟前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你021423 分钟前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
心疼你的一切40 分钟前
Python自动发邮件实战定时发报表
大数据·开发语言·python
步行cgn1 小时前
Spring MVC + Thymeleaf 模板解析失败:从 500 错误到页面正常显示
java·spring·mvc
ZhengEnCi1 小时前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
lgcgkCQ2 小时前
【AI 转型实战 1】SpringAI 入门:搭建基础大模型对话能力
java·ai·agent·rag·spring ai·mcp·langchain4j
Wang's Blog2 小时前
Java 项目实战:交友项目 - 用户体系集成总结
java·开发语言·交友
学到老活到老2 小时前
第 24 集:配置文件写了 80,Spring Boot 为什么读到 90?
java·后端·spring