In my previous article, we explored how to use cookies in Postman to store your secrets. Depending on your security requirements, you may need to use cryptography. This is where CryptoJS can help.
Script to Generate an Encrypted Secret
We can use a local Node.js script with the CryptoJS library to encrypt the secret. The example below shows how we will encrypt an API key.
const CryptoJS = require('crypto-js');
const { API_KEY: apiKey, SECRET_KEY: secretKey } = process.env;
const encryptedText = CryptoJS.AES.encrypt(apiKey, secretKey).toString();
console.log('encryptedText:', encryptedText);
We set the API key and secret key (used to encrypt the API key) as environment variables. That way we do not hardcode data into our script.
Using the Encrypted Secret and the Secret Key in Postman
We will store the secret key as a cookie to avoid sharing the value, and will store the encrypted API key as an environment variable.
We whitelist a cookie domain.
We create a cookie to store the secret key.
We create an environment variable that has the encrypted API key.
We create a pre-request script to get the secret key from the cookie, decrypt the encrypted API key from the environment variable, and set a temporary variable (Postman Sessions) with the plaintext API key.
// https://postman-quick-reference-guide.readthedocs.io/en/latest/libraries.html
const cookieJar = pm.cookies.jar();
const sessionVarName = "xApiKey";
const cookieName = "secretKey";
const domain = "postman.galaxy.demo";
cookieJar.get(domain, cookieName, (error, secretKey) => {
if (error) {
console.error(error);
pm.variables.set(sessionVarName, "error");
}
if (secretKey) {
// decryption
console.log('secretKey', secretKey);
const xApiKeyEnc = pm.environment.get('x-api-key-enc');
console.log('xApiKeyEnc', xApiKeyEnc);
const xApiKey = CryptoJS.AES.decrypt(xApiKeyEnc, secretKey).toString(CryptoJS.enc.Utf8);
console.log('xApiKey', xApiKey);
pm.variables.set(sessionVarName, xApiKey);
} else {
console.error("Cookie is missing")
pm.variables.set(sessionVarName, "missing");
}
});
We write a test to explicitly delete the xApiKey
variable after the request completes.
pm.variables.unset("xApiKey");
We can use the xApiKey
variable to use the plaintext API key.
Conclusion
By using cookies, we can use a secret key while avoiding sharing it. By using CryptoJS, we can store encrypted data in an environment variable, decrypt it, and use the plaintext (i.e., decrypted) data only during the request execution.
Before you go
About the author
Photo by Food Photographer | Jennifer Pallian on Unsplash