|
/** |
|
* https://github.com/botverse/node-rails-cookies |
|
* copied here because the project was abandoned |
|
*/ |
|
|
|
const crypto = require('crypto'); |
|
|
|
export function railsCookieDecrypt(options) { |
|
// linear time comparison |
|
function compare(a, b) { |
|
if ( a.length !== b.length ) { |
|
return false; |
|
} |
|
|
|
let result = 0; |
|
for (let i = 0; i < a.length; i++) { |
|
result |= a[i] ^ b[i]; /* tslint:disable-line */ |
|
} |
|
|
|
return 0 === result; |
|
} |
|
const secret = crypto.pbkdf2Sync(options.base, options.salt, options.iterations, options.keylen / 2, 'sha1'); |
|
const signed_secret = crypto.pbkdf2Sync(options.base, options.signed_salt, options.iterations, options.keylen, 'sha1'); |
|
|
|
return (cookie, cipherName) => { |
|
const signed_parts = cookie.split('--'); |
|
const hmac = crypto.createHmac('sha1', signed_secret); |
|
hmac.update(signed_parts[0]); |
|
const digest = hmac.digest('hex'); |
|
|
|
if (!compare(signed_parts[1], digest)) { |
|
return console.log('not valid'); |
|
} |
|
|
|
const message = new Buffer(signed_parts[0], 'base64').toString(); |
|
const parts = message.split('--').map(part => new Buffer(part, 'base64')); |
|
const cipher = crypto.createDecipheriv(cipherName, secret, parts[1]); |
|
const part = new Buffer(cipher.update(parts[0])).toString('utf8'); |
|
const final = cipher.final('utf8'); |
|
|
|
return [part, final].join(''); |
|
}; |
|
} |
|
|
|
|
|
|
|
// TODO turn into jasmine spec |
|
|
|
import {railsCookieDecrypt} from './rails-cookie-decrypt'; |
|
|
|
const cookie = "M2k2ZHU3cGlwWDZEd2t4WDcvWG1LcE9OZjVnZml6MytUeTNHUmw1VkFRUGhMZjJWNWYwRVBHcUtDUzBaRUJGYy0tRUg5NmZxaDFidmx6eVVSem5yZ0hFdz09--498b4639625f80077f8865e43aee2304e759fde7" |
|
const params = { |
|
base: 'f927223a2101b81b20b36d4d19244af018e9ec75b7f37555d3f732285172dfe71a7c54623d67de2f81f50905449d8833a45e738fbb5cc2fe5e988d7be7c6c36a' |
|
, salt: 'encrypted cookie' |
|
, signed_salt: 'signed encrypted cookie' |
|
, iterations: 1000 |
|
, keylen: 64 |
|
}; |
|
const cipher = 'aes-256-cbc'; |
|
|
|
const decryptor = railsCookieDecrypt(params); |
|
const message = decryptor(cookie, cipher); |
|
const json = JSON.parse(message); |
|
|
|
// Should output: { alt_key: 'DEE64795458447BB9B55' } |
|
console.log(json); |