0

I'm developing a Spring Boot application and I need to pass a default parameter to every select query from a table.

This in order to get some previously encrypted user data.

Ex:

select
         a.ID,
         CAST(AES_DECRYPT(a.FIRST_NAME, SHA2(#{secretKey}, 512)) AS CHAR) FIRST_NAME,
         CAST(AES_DECRYPT(a.LAST_NAME, SHA2(#{secretKey}, 512)) AS CHAR) LAST_NAME,
         USERNAME,
         PASSWD,
         b.ID ID_ROLE,
         b.NAME ROLE_NAME
       from users a join
       roles b on a.ID_ROLE = b.ID
       where
        USERNAME = #{username,jdbcType=VARCHAR} 

I'm using the mybatis-spring library with a SqlSessionFactoryBean configured in this way

SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:sqlmaps/*.xml"));
        sessionFactory.setDataSource(ds);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.getVariables().put("secretKey", "my secret key");        
        configuration.setCallSettersOnNulls(true);
        sessionFactory.setConfiguration(configuration);
        return sessionFactory;

But the "secretKey" It's not passed to the query.

What's the correct way to achieve this?

Thanks.

1 Answer 1

2

#{} is for referencing parameter(s) and its properties.
To reference variables, you need to use ${}.

As ${} is string substitution, it must be enclosed in single quotes and it is your responsibility to escape special characters like ' in the string.

SHA2('${secretKey}', 512)

Note that this solution is not recommended when secretKey is user-provided string because it is vulnerable to SQL injection attack.

Sign up to request clarification or add additional context in comments.

5 Comments

Beware. I don't think this is a correct answer. ${} shouldn't be used indiscriminately. It's open to SQL Injection and should be used only when you control the source of the parameter; that is, the parameter does not come from outside the code base (like the UI, a file, etc.).
In the provided code, secretKey is put into the configuration, so I assumed that it is not a user-provided string.
Then, all is good. Just wanted to make sure the OP won't use this strategy the wrong way.
Added a note as it's a very important point. Thank you for the comment, @TheImpaler !
@TheImpaler can confirm that the secret key is passed by configuration so It's safe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.