EncryptionUtil.java 3.51 KB
package com.template.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Random;

/**
 * 敏感数据加密解密
 */
public class EncryptionUtil {

    // AES加密
    public static String encrypt(String data, String key, String salt) throws Exception {
        // 生成密钥
        byte[] keyBytes = generateKey(key, salt);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        // 初始化向量
        byte[] ivBytes = new byte[16];
        System.arraycopy(keyBytes, 0, ivBytes, 0, Math.min(keyBytes.length, ivBytes.length));
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        // 加密
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));

        // 返回Base64编码的密文
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // AES解密
    public static String decrypt(String encryptedData, String key, String salt) throws Exception {
        // 生成密钥
        byte[] keyBytes = generateKey(key, salt);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        // 初始化向量
        byte[] ivBytes = new byte[16];
        System.arraycopy(keyBytes, 0, ivBytes, 0, Math.min(keyBytes.length, ivBytes.length));
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        // 解密
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));

        // 返回解密后的字符串
        return new String(decryptedBytes, "UTF-8");
    }

    // 生成密钥(加盐)
    private static byte[] generateKey(String key, String salt) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        byte[] keyBytes = (key + salt).getBytes("UTF-8");
        keyBytes = sha.digest(keyBytes);
        return keyBytes;
    }

    // 方法:生成指定长度的随机字符串
    public static String generateRandomString(int length) {
        // 定义字符集(可以根据需要修改字符集)
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        // 创建一个随机数生成器
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);

        // 随机选择字符并拼接
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        try {
            String data = "Hello, World!";
            String key = "youhehulian"; // 密钥
            String salt = generateRandomString(8);    // 盐值
            System.out.println("salt:"+salt);

            // 加密
            String encryptedData = encrypt(data, key, salt);
            System.out.println("Encrypted Data: " + encryptedData);

            // 解密
            String decryptedData = decrypt(encryptedData, key, salt);
            System.out.println("Decrypted Data: " + decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}