Search code examples
javaspring-mvccoding-stylesensitive-data

Java and Web development: good practices to store custom sensitive data such as private keys, API keys, etc


What do you advise to store custom sensitive data within a Spring MVC application (or within any other JAVA Web MVC application actually)? Let's say I've an API key and I need it to be available for my controllers. Several solutions I could think about:

1- Using a static class:

public final static String API_KEY = "my-api-key";

2- Using a context parameter (web.xml):

<context-param>
    <param-name>apiKey</param-name>
    <param-value>my-api-key</param-value>
</context-param>

3- Using a custom .properties file:

apiKey=my-api-key

4- Using a custom .xml file:

<entry key="apiKey">my-api-key</entry>

5- Any other idea/solution you could have :)

Thanks.


Solution

  • Depends on how secure you need that information to be.

    In options listed by you, I believe option (1)

    public final static String API_KEY = "my-api-key";
    

    is relatively safe as it the java file is compiled to class file and quick inspection of your distribution will not allow anyone to see the api-key, but downside is that it gets hard-coded and you cannot change it without a recompile.

    I would suggest having a hard-coded password in code and then encrypt the key using something like DES. The encrypted key then can be stored as a properties file or whatever.