-
Notifications
You must be signed in to change notification settings - Fork 13
nodejs cookies
Stephen von Takach edited this page Apr 17, 2020
·
1 revision
From @jackturnbull
I've been looking at Cloudflare Workers to handle some stateless tasks and wanted to see if there was an easy enough way that I could decrypt the session cookie so that I could get some user state/authentication within the worker. I haven't tried this out on Cloudflare workers themselves, but just wanted to prove that I could in fact decrypt the cookie. I've kept the function signatures somewhat similar to MessageEncryptor and MessageVerifier. If anyone wishes to give this a go...
Write the following to cookie_decryptor.js
const crypto = require("crypto");
const ENCRYPTION_KEY = process.env.COOKIE_SESSION_SECRET;
const COOKIE = "8uM6iNoyhsZh48P7AbLYj1YyUC6VTIha00GVUuKAWekHOcIa9EhDcjiNA0InjjB1LjxPZ53UygMMBOZl7lSXmA==--vXf2K/e1vInPU5Z0MWYl5h3GlFQ=";
function validMessage(encodedData, encodedDigest) {
const digest = Buffer.from(encodedDigest, "base64");
return encodedData.length > 0 && digest.length > 0 && crypto.timingSafeEqual(digest, generateDigest(encodedData));
}
function generateDigest(data) {
return crypto.createHmac("sha1", Buffer.from(ENCRYPTION_KEY)).update(data).digest();
}
function verify(signedMessage) {
const cookieSplit = signedMessage.split("--");
const encodedData = cookieSplit[0];
const encodedDigest = cookieSplit[1];
if (validMessage(encodedData, encodedDigest)) {
return Buffer.from(encodedData, "base64");
} else {
throw new Error("InvalidSignatureError");
}
}
function decrypt(message) {
const data = verify(message);
const iv = data.slice(-16);
const encryptedText = data.slice(0, -16);
const decipher = crypto.createDecipheriv("aes-256-cbc", new Buffer.from(ENCRYPTION_KEY), iv);
const decrypted = Buffer.concat([decipher.update(encryptedText), decipher.final()]);
return JSON.parse(decrypted.toString());
}
console.log(decrypt(COOKIE));
Run the script, setting the COOKIE_SESSION_SECRET environment variable:
COOKIE_SESSION_SECRET=4f74c0b358d5bab4000dd3c75465dc2c node cookie_decryptor.js