为了安全地存储敏感数据,需要采用以下措施:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String KEY = "mysecretkey12345"; // 加密密钥
public static String encrypt(String data) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String encryptedData) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decoded = Base64.getDecoder().decode(encryptedData.getBytes());
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted);
}
}
访问控制:只有授权的用户可以访问敏感数据。可以通过授权、认证和角色管理等方式来控制访问权限。
防止注入攻击:避免在SQL语句中使用动态拼接输入参数,而是使用参数绑定和预编译的方式来处理输入参数。以下是使用JDBC预编译语句处理查询的示例代码:
import java.sql.*;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private static