Search code examples
goencryption

How to encrypt/decrypt a dynamic SQL query in Golang with a fixed-size encrypted result?


I have a Golang application where I dynamically generate SQL queries based on struct comparisons, the data type of this results is a string. Like:

"SELECT id FROM table WHERE column_a = value_a AND column_b IN (value_b, value_c)"

The WHERE clause will be dynamic, we can have n conditions.

For security purposes, I want to encrypt the query result to store it in a database, and later I need to decrypt it for a execution in a job process.

I would like that the encryption produces a fixed-size result to ensure consistency in the database, and also to prevent an error if the encrypted result is too large to save in the database, for example if I have a limit of 255 characters, error reference: SQL Error 1406 (Data too long).

I tried with this example https://go.dev/play/p/VXD0j_DuycG, but the result increases in size if the input is longer.

Is it possible to achieve? Someone knows a guidance or documentation that could be helpful for this case?

Any guidance or documentation on how to approach this problem would be helpful, thanks!


Solution

  • Even if you only use procedures, security issues are largely resolved.

    example...

    delimiter //
    CREATE OR REPLACE PROCEDURE Something(vals JSON)
    BEGIN
        SELECT id
        FROM TABLE
        WHERE column_a = value_a AND json_contains(vals, column_b, '$');
    END//
    

    CALL Something('["value_b", "value_c"]');

    If you want, you can also use json functions to do things like type checking.

    and... I don't think it's desirable, but if you use the query in the above procedure, I think you can create a fixed-length query.