Encrypting Sensitive Data Before Storing in Cookies

Loading

Storing sensitive data in cookies without encryption can lead to security risks, including session hijacking, data leaks, and cross-site scripting (XSS) attacks. Encrypting sensitive data before storing it in cookies ensures confidentiality, integrity, and security.

This guide will cover:
✔ Why encrypt cookie data
✔ How to encrypt and decrypt data before storing it in cookies
✔ Best practices for secure cookie storage


1. Why Encrypt Cookies?

Cookies often store user authentication tokens, session IDs, preferences, and sensitive data. If cookies are stolen or tampered with, attackers can impersonate users, steal personal data, or exploit security vulnerabilities.

Common Security Threats to Cookies

Session Hijacking – Attackers steal session cookies to take over user accounts.
Cross-Site Scripting (XSS) – Malicious scripts can access cookies and send them to attackers.
Cross-Site Request Forgery (CSRF) – Attackers trick users into making unauthorized requests.
Cookie Tampering – Attackers modify cookie values to gain unauthorized access.

Solution: Encrypt Cookie Data

Encrypting cookies ensures that even if an attacker steals them, the data remains unreadable.
Hashing session IDs prevents tampering.
Using secure attributes strengthens protection.


2. How to Encrypt and Store Cookies Securely

A. Setting Secure Cookies in AngularJS

AngularJS does not provide built-in cookie encryption, so we must use third-party libraries such as CryptoJS.

Install CryptoJS

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

B. Encrypting Data Before Storing in Cookies

To securely store cookies, use AES (Advanced Encryption Standard) to encrypt data.

Example: Encrypt and Set Cookie

app.service('SecureCookieService', ['$cookies', function($cookies) {
var secretKey = "mySuperSecretKey"; // Use a strong secret key

this.setEncryptedCookie = function(cookieName, data, expirationDays) {
var encryptedData = CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString();
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + expirationDays);

$cookies.put(cookieName, encryptedData, {
secure: true, // Only accessible over HTTPS
httpOnly: false, // Prevents client-side JavaScript from accessing it
expires: expireDate
});
};

this.getDecryptedCookie = function(cookieName) {
var encryptedData = $cookies.get(cookieName);
if (!encryptedData) return null;

var bytes = CryptoJS.AES.decrypt(encryptedData, secretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
};

this.deleteCookie = function(cookieName) {
$cookies.remove(cookieName);
};
}]);

How It Works:
✔ Encrypts sensitive data using AES encryption before storing it.
✔ Decrypts the cookie when retrieving data.
✔ Secure cookies prevent unauthorized access.


C. Securely Storing Authentication Tokens

Instead of storing JWT tokens in localStorage, store them in secure, encrypted cookies.

Example: Encrypt JWT Token Before Storing in Cookie

var token = "your-jwt-token";
SecureCookieService.setEncryptedCookie("authToken", token, 7);

Example: Retrieve and Decrypt JWT Token

var token = SecureCookieService.getDecryptedCookie("authToken");
console.log("Decrypted Token:", token);

3. Best Practices for Secure Cookie Storage

1. Use Secure and HttpOnly Flags

Ensure cookies are only transmitted over HTTPS and cannot be accessed via JavaScript.

document.cookie = "authToken=encryptedData; Secure; HttpOnly; SameSite=Strict";

2. Set SameSite Attribute to Prevent CSRF

Use SameSite=Strict to prevent cross-site request forgery (CSRF) attacks.

SameSite=Strict; Secure

3. Avoid Storing Sensitive Data in Cookies

Do not store passwords, financial data, or personal information in cookies.

4. Implement Expiration Policies

Always set an expiration date to limit exposure.

expires=Fri, 31 Dec 2025 23:59:59 GMT

5. Regularly Rotate Encryption Keys

Use different encryption keys and rotate them periodically.

Leave a Reply

Your email address will not be published. Required fields are marked *