Secure storage and retrieval of sensitive information, such as API keys, in source code
package com.example;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AppServlet extends HttpServlet {
private static final String API_KEY = "1234567890abcdef"; // Sensitive information
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Use the API key in some way...
}
}
In the above code, we have a
HttpServlet
named
AppServlet
. The variable
API_KEY
is declared as a static final string and is initialized with a hardcoded value. This API key represents sensitive information.
This is a security vulnerability because the API key is stored in the source code in plain text. Anyone who has access to the source code can see this key. If this source code is pushed to a public repository, then anyone can have access to this key.
Furthermore, the key is not obtained from a secure source that guarantees its confidentiality. It's hardcoded and does not change, making it easy for an attacker to use this key for malicious purposes.
The best practice is to not store sensitive information in the source code. Instead, sensitive information should be stored in environment variables or in a secure key vault.
To fix this vulnerability, the API key should be removed from the source code and stored securely. The key should then be accessed through secure means, such as an environment variable or a secure key management system.
package com.example;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AppServlet extends HttpServlet {
private static String API_KEY; // Sensitive information
@Override
public void init() throws ServletException {
API_KEY = System.getenv("API_KEY");
if (API_KEY == null) {
throw new ServletException("API_KEY not set in environment variables");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Use the API key in some way...
}
}
The API key is no longer stored in the source code. Instead, it is retrieved from an environment variable at runtime. This is done in the
init()
method, which is called when the servlet is first created. If the API key is not set in the environment variables, a
ServletException
is thrown.
To set the API key as an environment variable, you can use the following command in a UNIX-based system:
export API_KEY=your_api_key
setx API_KEY "your_api_key"
your_api_key
with your actual API key.