Java数据保护案例

wen java案例 3

本文目录导读:

Java数据保护案例

  1. 用户密码加密存储案例
  2. 数据脱敏处理案例
  3. AES加密解密案例
  4. HTTPS通信配置案例
  5. 数据库敏感字段加密案例
  6. 日志脱敏工具案例
  7. 注意事项

我来为您提供几个实用的Java数据保护案例,涵盖加密、脱敏和安全传输等场景。

用户密码加密存储案例

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class PasswordProtection {
    // 使用bcrypt算法加密密码(推荐方案)
    public static class BCryptPasswordHasher {
        private static final int STRENGTH = 10; // 工作因子
        public static String hashPassword(String password) {
            return BCrypt.hashpw(password, BCrypt.gensalt(STRENGTH));
        }
        public static boolean checkPassword(String password, String hashedPassword) {
            return BCrypt.checkpw(password, hashedPassword);
        }
    }
    // 使用SHA-256 + 盐值加密密码(传统方案)
    public static class SHA256PasswordHasher {
        public static String hashPassword(String password, String salt) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                String saltedPassword = password + salt;
                byte[] hash = md.digest(saltedPassword.getBytes());
                StringBuilder hexString = new StringBuilder();
                for (byte b : hash) {
                    hexString.append(String.format("%02x", b));
                }
                return hexString.toString();
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("SHA-256 algorithm not found", e);
            }
        }
        public static String generateSalt() {
            SecureRandom random = new SecureRandom();
            byte[] salt = new byte[16];
            random.nextBytes(salt);
            return Base64.getEncoder().encodeToString(salt);
        }
    }
    // 使用示例
    public static void main(String[] args) {
        // BCrypt示例
        String password = "MySecurePassword123!";
        String hashedPassword = BCryptPasswordHasher.hashPassword(password);
        System.out.println("BCrypt Hashed: " + hashedPassword);
        System.out.println("Verify: " + BCryptPasswordHasher.checkPassword(password, hashedPassword));
        // SHA-256示例
        String salt = SHA256PasswordHasher.generateSalt();
        String sha256Hashed = SHA256PasswordHasher.hashPassword(password, salt);
        System.out.println("SHA-256 Hashed: " + sha256Hashed);
    }
}

数据脱敏处理案例

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DataDesensitization {
    // 手机号脱敏
    public static String maskPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.length() < 7) {
            return phoneNumber;
        }
        return phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }
    // 身份证号脱敏
    public static String maskIdCard(String idCard) {
        if (idCard == null || idCard.length() < 10) {
            return idCard;
        }
        return idCard.replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1**********$2");
    }
    // 邮箱脱敏
    public static String maskEmail(String email) {
        if (email == null || !email.contains("@")) {
            return email;
        }
        String[] parts = email.split("@");
        String username = parts[0];
        String domain = parts[1];
        if (username.length() <= 2) {
            return username.charAt(0) + "***@" + domain;
        }
        return username.substring(0, 2) + "***@" + domain;
    }
    // 银行卡号脱敏
    public static String maskBankCard(String cardNumber) {
        if (cardNumber == null || cardNumber.length() < 8) {
            return cardNumber;
        }
        return cardNumber.replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1 **** **** $2");
    }
    // 姓名脱敏
    public static String maskName(String name) {
        if (name == null || name.length() <= 1) {
            return name;
        }
        if (name.length() == 2) {
            return name.charAt(0) + "*";
        }
        StringBuilder masked = new StringBuilder();
        masked.append(name.charAt(0));
        for (int i = 1; i < name.length() - 1; i++) {
            masked.append("*");
        }
        masked.append(name.charAt(name.length() - 1));
        return masked.toString();
    }
    // 使用示例
    public static void main(String[] args) {
        System.out.println("手机号: " + maskPhoneNumber("13812345678"));
        System.out.println("身份证: " + maskIdCard("110101199001011234"));
        System.out.println("邮箱: " + maskEmail("zhangsan@example.com"));
        System.out.println("银行卡: " + maskBankCard("6217001234567890123"));
        System.out.println("姓名: " + maskName("张三丰"));
    }
}

AES加密解密案例

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
public class AESEncryption {
    private static final int AES_KEY_SIZE = 256;
    private static final int GCM_IV_LENGTH = 12;
    private static final int GCM_TAG_LENGTH = 16; // 128位
    // 生成AES密钥
    public static SecretKey generateAESKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(AES_KEY_SIZE);
        return keyGenerator.generateKey();
    }
    // AES-GCM加密
    public static String encrypt(String plaintext, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        // 生成随机IV
        byte[] iv = new byte[GCM_IV_LENGTH];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmSpec);
        byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
        // 将IV和密文组合在一起
        byte[] encrypted = new byte[iv.length + ciphertext.length];
        System.arraycopy(iv, 0, encrypted, 0, iv.length);
        System.arraycopy(ciphertext, 0, encrypted, iv.length, ciphertext.length);
        return Base64.getEncoder().encodeToString(encrypted);
    }
    // AES-GCM解密
    public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
        byte[] decoded = Base64.getDecoder().decode(encryptedData);
        // 提取IV和密文
        byte[] iv = new byte[GCM_IV_LENGTH];
        byte[] ciphertext = new byte[decoded.length - GCM_IV_LENGTH];
        System.arraycopy(decoded, 0, iv, 0, iv.length);
        System.arraycopy(decoded, iv.length, ciphertext, 0, ciphertext.length);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmSpec);
        byte[] plaintext = cipher.doFinal(ciphertext);
        return new String(plaintext);
    }
    // 使用示例
    public static void main(String[] args) throws Exception {
        SecretKey key = generateAESKey();
        String originalData = "这是需要加密的敏感数据!";
        String encrypted = encrypt(originalData, key);
        System.out.println("加密后: " + encrypted);
        String decrypted = decrypt(encrypted, key);
        System.out.println("解密后: " + decrypted);
        // 验证
        System.out.println("是否一致: " + originalData.equals(decrypted));
    }
}

HTTPS通信配置案例

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class HTTPSExample {
    // 配置信任自签名证书
    public static SSLContext createSSLContext(String certPath, String password) throws Exception {
        // 加载证书
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        FileInputStream certInputStream = new FileInputStream(certPath);
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(certInputStream);
        certInputStream.close();
        // 创建KeyStore
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("customCert", certificate);
        // 创建TrustManager
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        // 创建SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        return sslContext;
    }
    // 忽略证书验证(仅用于开发环境!)
    public static SSLContext createInsecureSSLContext() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            }
        };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        return sslContext;
    }
    // 使用HTTPS发送请求
    public static String sendHTTPSRequest(String urlString, SSLContext sslContext) throws Exception {
        URL url = new URL(urlString);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }
    // 使用示例
    public static void main(String[] args) {
        try {
            // 开发环境使用不安全的SSL
            SSLContext sslContext = createInsecureSSLContext();
            String response = sendHTTPSRequest("https://api.example.com/data", sslContext);
            System.out.println("HTTPS响应: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

数据库敏感字段加密案例

import javax.persistence.*;
import java.util.Base64;
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    @Convert(converter = SensitiveDataConverter.class)
    private String phoneNumber;
    @Convert(converter = SensitiveDataConverter.class)
    private String email;
    // getters and setters
}
// JPA属性转换器
@Converter
public class SensitiveDataConverter implements AttributeConverter<String, String> {
    private static final String ENCRYPTION_KEY = "your-encryption-key-here";
    @Override
    public String convertToDatabaseColumn(String attribute) {
        if (attribute == null) {
            return null;
        }
        // 加密逻辑
        return encrypt(attribute);
    }
    @Override
    public String convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return null;
        }
        // 解密逻辑
        return decrypt(dbData);
    }
    private String encrypt(String value) {
        // 实际项目中应使用AES等加密算法
        return Base64.getEncoder().encodeToString(value.getBytes());
    }
    private String decrypt(String value) {
        // 实际项目中应使用AES等加密算法
        return new String(Base64.getDecoder().decode(value));
    }
}

日志脱敏工具案例

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class LogDesensitizer {
    private static final Map<Pattern, String> PATTERNS = new HashMap<>();
    static {
        // 手机号
        PATTERNS.put(Pattern.compile("(1[3-9]\\d)\\d{4}(\\d{4})"), "$1****$2");
        // 身份证
        PATTERNS.put(Pattern.compile("(\\d{6})\\d{8}(\\d{4})"), "$1********$2");
        // 银行卡
        PATTERNS.put(Pattern.compile("(\\d{4})\\d{10}(\\d{4})"), "$1****$2");
        // 邮箱
        PATTERNS.put(Pattern.compile("(\\w{2})\\w+(@\\w+\\.\\w+)"), "$1***$2");
        // IP地址
        PATTERNS.put(Pattern.compile("(\\d{1,3}\\.\\d{1,3})\\.\\d{1,3}\\.\\d{1,3}"), "$1.*.*");
    }
    public static String desensitize(String logMessage) {
        String result = logMessage;
        for (Map.Entry<Pattern, String> entry : PATTERNS.entrySet()) {
            result = entry.getKey().matcher(result).replaceAll(entry.getValue());
        }
        return result;
    }
    // 使用示例
    public static void main(String[] args) {
        String log = "用户 13812345678 使用邮箱 testuser@example.com 登录,IP: 192.168.1.100";
        System.out.println("原始日志: " + log);
        System.out.println("脱敏后: " + desensitize(log));
    }
}

注意事项

  1. 密钥管理:不要将密钥硬编码在代码中,应使用密钥管理服务
  2. 密码算法:密码存储推荐使用bcrypt、scrypt或argon2
  3. 传输安全:生产环境必须使用有效的SSL/TLS证书
  4. 合规要求:遵守GDPR、个人数据保护法等法规
  5. 性能考虑:加密操作会影响性能,需要合理设计缓存策略

这些案例涵盖了Java数据保护的常见场景,可以根据实际需求进行调整和扩展。

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