Java加密工具案例如何编写

wen java案例 28

本文目录导读:

Java加密工具案例如何编写

  1. 完整加密工具类
  2. 使用示例
  3. 使用建议
  4. 注意事项

我来为你提供一个Java加密工具类的完整案例,包含常见的对称加密(AES)、非对称加密(RSA)和散列函数(SHA-256)。

完整加密工具类

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.Base64;
/**
 * Java加密解密工具类
 * 支持:AES对称加密、RSA非对称加密、SHA-256散列
 */
public class CryptoUtils {
    private static final String CHARSET = "UTF-8";
    // ==================== AES对称加密 ====================
    /**
     * 生成AES密钥
     * @param keySize 密钥长度(128/192/256)
     * @return Base64编码的密钥
     */
    public static String generateAESKey(int keySize) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(keySize);
        SecretKey secretKey = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }
    /**
     * AES加密
     * @param plainText 明文
     * @param base64Key Base64编码的密钥
     * @return Base64编码的密文
     */
    public static String aesEncrypt(String plainText, String base64Key) throws Exception {
        // 解码密钥
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        // 创建IV向量(随机生成)
        byte[] ivBytes = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(ivBytes);
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        // 初始化加密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        // 加密
        byte[] plainBytes = plainText.getBytes(CHARSET);
        byte[] encryptedBytes = cipher.doFinal(plainBytes);
        // 组合IV和密文(IV在前,密文在后)
        byte[] result = new byte[ivBytes.length + encryptedBytes.length];
        System.arraycopy(ivBytes, 0, result, 0, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, result, ivBytes.length, encryptedBytes.length);
        return Base64.getEncoder().encodeToString(result);
    }
    /**
     * AES解密
     * @param encryptedText Base64编码的密文
     * @param base64Key Base64编码的密钥
     * @return 明文
     */
    public static String aesDecrypt(String encryptedText, String base64Key) throws Exception {
        // 解码密钥
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        // 解码密文(包含IV)
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        // 提取IV
        byte[] ivBytes = new byte[16];
        System.arraycopy(encryptedBytes, 0, ivBytes, 0, 16);
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        // 提取真正的密文
        byte[] realEncryptedBytes = new byte[encryptedBytes.length - 16];
        System.arraycopy(encryptedBytes, 16, realEncryptedBytes, 0, realEncryptedBytes.length);
        // 初始化解密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        // 解密
        byte[] plainBytes = cipher.doFinal(realEncryptedBytes);
        return new String(plainBytes, CHARSET);
    }
    // ==================== RSA非对称加密 ====================
    /**
     * 生成RSA密钥对
     * @param keySize 密钥长度(建议2048以上)
     * @return 包含公钥和私钥的KeyPair对象
     */
    public static KeyPair generateRSAKeyPair(int keySize) throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize);
        return keyGen.generateKeyPair();
    }
    /**
     * 将公钥转换为Base64字符串
     */
    public static String publicKeyToBase64(PublicKey publicKey) {
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }
    /**
     * 将私钥转换为Base64字符串
     */
    public static String privateKeyToBase64(PrivateKey privateKey) {
        return Base64.getEncoder().encodeToString(privateKey.getEncoded());
    }
    /**
     * 从Base64字符串恢复公钥
     */
    public static PublicKey base64ToPublicKey(String base64Key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }
    /**
     * 从Base64字符串恢复私钥
     */
    public static PrivateKey base64ToPrivateKey(String base64Key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }
    /**
     * RSA加密(使用公钥)
     */
    public static String rsaEncrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    /**
     * RSA解密(使用私钥)
     */
    public static String rsaDecrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] plainBytes = cipher.doFinal(encryptedBytes);
        return new String(plainBytes, CHARSET);
    }
    // ==================== SHA-256散列 ====================
    /**
     * 计算SHA-256散列值
     * @param input 输入字符串
     * @return 十六进制表示的散列值
     */
    public static String sha256(String input) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(input.getBytes(CHARSET));
        return bytesToHex(hash);
    }
    /**
     * 带盐值的SHA-256散列
     */
    public static String sha256WithSalt(String input, String salt) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(salt.getBytes(CHARSET));
        byte[] hash = digest.digest(input.getBytes(CHARSET));
        return bytesToHex(hash);
    }
    // ==================== 辅助方法 ====================
    /**
     * 字节数组转十六进制字符串
     */
    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();
    }
}

使用示例

public class CryptoDemo {
    public static void main(String[] args) {
        try {
            String originalText = "Hello, Java加密工具!";
            // 1. AES加密测试
            System.out.println("=== AES加密测试 ===");
            String aesKey = CryptoUtils.generateAESKey(256);
            System.out.println("AES密钥: " + aesKey);
            String aesEncrypted = CryptoUtils.aesEncrypt(originalText, aesKey);
            System.out.println("AES密文: " + aesEncrypted);
            String aesDecrypted = CryptoUtils.aesDecrypt(aesEncrypted, aesKey);
            System.out.println("AES解密: " + aesDecrypted);
            // 2. RSA加密测试
            System.out.println("\n=== RSA加密测试 ===");
            KeyPair keyPair = CryptoUtils.generateRSAKeyPair(2048);
            String publicKeyStr = CryptoUtils.publicKeyToBase64(keyPair.getPublic());
            String privateKeyStr = CryptoUtils.privateKeyToBase64(keyPair.getPrivate());
            System.out.println("公钥: " + publicKeyStr);
            System.out.println("私钥: " + privateKeyStr);
            String rsaEncrypted = CryptoUtils.rsaEncrypt(originalText, keyPair.getPublic());
            System.out.println("RSA密文: " + rsaEncrypted);
            String rsaDecrypted = CryptoUtils.rsaDecrypt(rsaEncrypted, keyPair.getPrivate());
            System.out.println("RSA解密: " + rsaDecrypted);
            // 3. SHA-256散列测试
            System.out.println("\n=== SHA-256散列测试 ===");
            String hash1 = CryptoUtils.sha256(originalText);
            System.out.println("SHA-256: " + hash1);
            String salt = "randomSalt123";
            String hash2 = CryptoUtils.sha256WithSalt(originalText, salt);
            System.out.println("SHA-256(带盐): " + hash2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用建议

  1. AES加密适用于:大量数据的加密,如文件加密、数据库字段加密
  2. RSA加密适用于:少量关键数据的加密,如密钥交换、数字签名
  3. SHA-256适用于:密码存储、数据完整性校验

注意事项

  • AES密钥长度建议使用256位
  • RSA密钥长度建议使用2048位或以上
  • 生产环境请使用更安全的密钥管理方案
  • 密钥不要硬编码在代码中,建议使用配置中心或密钥管理服务

这个加密工具类提供了常用的加密功能,你可以根据实际需求进行扩展和优化。

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