Blog | G5 Cyber Security

Caching Sensitive Data Safely

TL;DR

Caching sensitive data can speed up your application but introduces security risks. This guide explains how to cache safely using short timeouts, encryption, and careful key management.

1. Understand the Risks

Caching stores copies of data. If that data is sensitive (passwords, personal details, financial information), a compromised cache can lead to serious breaches. Key risks include:

2. Minimise Cache Lifetime (TTL)

The shorter the time a piece of sensitive data is stored in the cache, the smaller the window for attackers. Use short Time-To-Live (TTL) values.

# Example (Redis) - set expiry to 60 seconds
SET my_sensitive_data "some value" EX 60

3. Encryption at Rest and in Transit

Always encrypt sensitive data before storing it in the cache, even if you trust the caching server itself.

# Example (Python) - encrypting data before storing
from cryptography.fernet import Fernet
key = b'YOUR_ENCRYPTION_KEY'
f = Fernet(key)
token = f.encrypt(b"my sensitive data")

4. Secure Cache Keys

Cache keys should not reveal sensitive information or be easily guessable.

# Example (JavaScript) - generating a secure key
import crypto from 'crypto';
const userId = 123;
const salt = crypto.randomBytes(16).toString('hex');
const dataToHash = userId + salt;
const hash = crypto.createHash('sha256').update(dataToHash).digest('hex');
const cacheKey = 'user_' + hash;

5. Access Control

Restrict access to the caching server and cached data.

6. Cache Invalidation

Ensure data is removed from the cache when it becomes invalid.

# Example (Redis) - deleting a key
DEL my_sensitive_data

7. Monitoring and Auditing

Regularly monitor your caching server for suspicious activity.

Exit mobile version