ITPub博客

首页 > 应用开发 > Java > java处理敏感数据的加密方法

java处理敏感数据的加密方法

原创 Java 作者:mingtian66 时间:2024-10-24 16:12:19 0 删除 编辑

在 Java 中,处理敏感数据(如密码、个人信息等)时,通常需要对数据进行加密,以确保数据的安全性和隐私性。Java 提供了多个类库来实现加密,包括对称加密、非对称加密和哈希算法。以下是常见的加密方法及其实现:
常见加密方法

    对称加密:使用单一密钥进行加密和解密(如 AES)。
    非对称加密:使用一对密钥(公钥和私钥)进行加密和解密(如 RSA)。
    哈希算法:对数据生成固定长度的摘要,不可逆(如 SHA-256)。

1. 对称加密(AES)

AES(Advanced Encryption Standard)是一种常用的对称加密算法,适用于大多数场景。它使用相同的密钥进行加密和解密。
AES 加密和解密示例:

java

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesEncryption {

    // 生成 AES 密钥
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // 选择 AES-128,安全级别可以是128、192、256
        return keyGen.generateKey();
    }

    // 加密
    public static String encrypt(String data, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes); // 将加密结果编码为 Base64 字符串
    }

    // 解密
    public static String decrypt(String encryptedData, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        String data = "Sensitive Data";

        // 生成密钥
        SecretKey key = generateKey();

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

        // 解密数据
        String decryptedData = decrypt(encryptedData, key);
        System.out.println("Decrypted Data: " + decryptedData);
    }
}

说明:

    AES 算法:Cipher.getInstance("AES") 使用 AES 算法加密和解密。
    Base64 编码:加密后的二进制数据通过 Base64 编码成字符串便于传输和存储。

2. 非对称加密(RSA)

RSA 是一种常用的非对称加密算法,使用公钥加密,私钥解密,适用于安全传输和身份验证。
RSA 加密和解密示例:

java

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RsaEncryption {

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

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

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

    public static void main(String[] args) throws Exception {
        String data = "Sensitive Data";

        // 生成密钥对
        KeyPair keyPair = generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

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

        // 解密数据
        String decryptedData = decrypt(encryptedData, privateKey);
        System.out.println("Decrypted Data: " + decryptedData);
    }
}

说明:

    RSA 密钥对:KeyPairGenerator 用来生成 RSA 密钥对(公钥和私钥)。
    公钥加密,私钥解密:加密使用公钥,解密使用私钥,确保信息只有拥有私钥的人可以解密。

3. 哈希算法(SHA-256)

哈希算法用于生成不可逆的摘要,例如用于密码存储。SHA-256 是常用的哈希算法之一。
SHA-256 示例:

java

import java.security.MessageDigest;

public class Sha256Hashing {

    // 生成 SHA-256 哈希
    public static String hash(String data) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(data.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();

        // 将每个字节转换为 16 进制格式
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    }

    public static void main(String[] args) throws Exception {
        String data = "Sensitive Data";
        String hashedData = hash(data);
        System.out.println("Hashed Data: " + hashedData);
    }
}

说明:

    不可逆性:哈希算法生成的数据摘要不可逆,用于验证数据完整性或加密存储密码。
    SHA-256:使用 MessageDigest.getInstance("SHA-256") 来实现哈希。

4. 使用加盐哈希存储密码

为了增强密码的安全性,通常会对密码加盐(增加随机值)后再进行哈希,这样可以避免彩虹表攻击。

java

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

public class SaltedHashing {

    // 生成随机盐
    public static String generateSalt() throws Exception {
        SecureRandom sr = new SecureRandom();
        byte[] salt = new byte[16];
        sr.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 生成带盐的哈希
    public static String hashWithSalt(String data, String salt) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        String saltedData = data + salt;
        byte[] hash = digest.digest(saltedData.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();

        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    }

    public static void main(String[] args) throws Exception {
        String password = "SensitivePassword";

        // 生成盐并哈希密码
        String salt = generateSalt();
        String saltedHash = hashWithSalt(password, salt);

        System.out.println("Salt: " + salt);
        System.out.println("Salted Hash: " + saltedHash);
    }
}

说明:

    生成盐:通过 SecureRandom 生成随机盐。
    带盐哈希:将盐与密码拼接后再进行哈希。

总结

    对称加密:使用 AES 加密和解密敏感数据。
    非对称加密:使用 RSA 进行安全数据传输和身份验证。
    哈希算法:使用 SHA-256 哈希不可逆的数据,如密码。
    加盐哈希:增加安全性,防止彩虹表攻击。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70040412/viewspace-3042707/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2024-08-07

  • 博文量
    589
  • 访问量
    602915