How to safely escape arbitrary strings for SQL in PostgreSQL using Java

后端 未结 2 2016
遇见更好的自我
遇见更好的自我 2021-02-04 06:19

I have a special case requiring that I generate part of a SQL WHERE clause from user supplied input values. I want to prevent any sort of SQL Injection vulnerability.

相关标签:
2条回答
  • 2021-02-04 06:26

    I asked a similar question here, but I think that the best thing to do is to use org.postgresql.core.Utils.escapeLiteral. This is a Postgres library so using it should be safe. If/when Postgres adds new string delimiters this method should be updated.

    0 讨论(0)
  • 2021-02-04 06:38

    The most easiest way would be to use PostgreSQL's Dollar Quoting in the combination with a small random tag:

    • For each invocation calculate a small, random tag (e.g 4 characters) (redundant)
    • Look whether or not the quote tag is part of the input string.
    • If it is, recalculate a new random tag.
    • Otherwise build your query like this:

      $tag$inputString$tag$
      

    This way you escape the whole hassle of different nested quoting techniques and you also set up a moving target by using a random tag.

    Depending on your security requirements this might do the job or not. :-)

    0 讨论(0)
提交回复
热议问题