对于前后端交互时需要脱敏处理的字段,可以使用加密算法对明文字段进行加密,并将加密后的结果存储到脱敏字段中返回给前端。前端在提交时将脱敏字段传回后端,后端可以通过解密算法对脱敏字段进行解密,还原成明文字段。

下面是一个Java实现的示例代码:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionUtils {

    private static final String ENCRYPTION_ALGORITHM = "AES";
    private static final String SECRET_KEY = "YourSecretKey"; // 这里使用的是对称加密算法,需要提供一个密钥

    public static String encrypt(String plaintext) throws Exception {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String ciphertext) throws Exception {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            // 加密示例
            String plaintext = "sensitive information";
            String encryptedText = encrypt(plaintext);
            System.out.println("Encrypted Text: " + encryptedText);

            // 解密示例
            String decryptedText = decrypt(encryptedText);
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在实际应用中,需要注意密钥的安全性,建议将密钥存储在安全的地方,如密钥管理系统中,并限制对密钥的访问权限。

对于前端读取脱敏字段的处理,可以截取脱敏字段的一部分作为展示,或者根据具体需求对脱敏字段进行解析处理,例如根据特定规则还原出一部分明文信息。具体的处理方式应根据业务场景和安全需求进行设计

前后端交互时只给返回脱敏字段对应的明文字段不返回给前端;然后前端提交时后端应该如何对这个脱敏字段进行还原?是否有合理的方法进行这种场景的脱敏处理例如对明文加密后拼接到脱敏字段上?前端读取是截取?请帮忙分析并给出合理的方案或JAVA实现代码

原文地址: https://www.cveoy.top/t/topic/ihJM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录