Java开发中常见的安全漏洞及解决方法
String sql = "SELECT * FROM users WHERE username = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, userInput); ResultSet resultSet = statement.executeQuery();
String userInput = "<script>alert('XSS attack');</script>"; String safeInput = StringEscapeUtils.escapeHtml4(userInput); System.out.println(safeInput);
// 在用户登录时生成CSRF令牌,并存储在Session中 String csrfToken = generateCSRFToken(); session.setAttribute("csrfToken", csrfToken); // 在提交表单时验证CSRF令牌的有效性 String userToken = request.getParameter("csrfToken"); String serverToken = session.getAttribute("csrfToken"); if (serverToken.equals(userToken)) { // 验证通过,执行敏感操作 // ... } else { // 验证失败,拒绝请求或采取其他安全措施 }
// 生成RSA密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 对明文进行加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); byte[] encryptedData = cipher.doFinal(plainText.getBytes()); // 对密文进行解密 cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); byte[] decryptedData = cipher.doFinal(encryptedData); // 对数据进行数字签名 Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(data); byte[] signatureData = signature.sign(); // 验证数字签名的合法性 Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(keyPair.getPublic()); signature.update(data); boolean isValid = signature.verify(signatureData);
以上是Java开发中常见的安全漏洞及解决方法的详细内容。更多信息请关注PHP中文网其他相关文章!