我目前正在开发一个Node.js脚本,它将我登录到一个网站,并在我登录时自动打开浏览器。我一直试图向chrome的" cookie“数据库中添加一个cookie(从登录POST请求中收集),但是我在加密方面失败了。关于Cookies的加密是这样的:Chrome 80 how to decode cookies,但是这个线程是关于解密一个cookie,而不是加密它。
function encryptCookie(cookie, key){
const iv = crypto.randomBytes(16);
let cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let encrypted = cipher.update(cookie);
encrypted = Buffer.concat([Buffer.from('v10'), encrypted, cipher.final()]);
console.log(`Encrypted: ${encrypted}`);
return encrypted;
}至于“密钥”,我使用的是来自地方政府的解密密钥。(我使用DPAPI模块解密密钥。)我知道加密的cookie总是以v10开头,所以我添加了它作为前缀,但是加密Cookie仍然太短。
我知道我可以使用webscraper或者只是在页面上安全地使用我的密码,但是我想要与cookie数据库和HTTP请求交互。
发布于 2020-09-22 07:36:54
在linked answer中,数据的结构描述如下:
加密的数据从v10的ASCII编码(即0x763130)开始,后面跟着12个字节的nonce、实际的密文,最后是16个字节的身份验证标记。
即数据结构如下:
IV
长度为:3+ 12 +密文长度+ 16。此外,由于GCM模式不使用填充,密文的长度与明文的长度相同。
除其他外,发布的代码使用错误的IV长度,不连接IV,也不考虑身份验证标记。
加密/解密的一个可能实现是:
var crypto = require('crypto');
function encryptCookie(cookie, key){
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const encryptedCookie = Buffer.concat(
[
Buffer.from('v10'), // prefix
iv, // 12 bytes nonce
cipher.update(cookie), // cookie data
cipher.final(),
cipher.getAuthTag() // 16 bytes authentication
]);
return encryptedCookie;
}
function decryptCookie(encryptedCookie, key){
const prefix = encryptedCookie.slice(0, 3); // prefix
const iv = encryptedCookie.slice(3, 3 + 12); // 12 bytes nonce
const ciphertext = encryptedCookie.slice(3 + 12, encryptedCookie.length - 16); // encrypted cookie
const authTag = encryptedCookie.slice(encryptedCookie.length - 16); // 12 bytes authentication tag
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
const decryptedCookie = Buffer.concat(
[
decipher.update(ciphertext), // encrypted cookie
decipher.final(),
]);
return decryptedCookie;
}
// Encryption
const cookie = Buffer.from('The test cookie with some data');
const key = Buffer.from('01234567890123456789012345678901');
const encryptedCookie = encryptCookie(cookie, key);
console.log(encryptedCookie);
console.log(encryptedCookie.length);
// Decryption
const decryptedCookie = decryptCookie(encryptedCookie, key);
console.log(decryptedCookie.toString('utf8'));对于长度为30字节的样例cookie,加密数据的长度为3+ 12 + 30 + 16 = 61字节。
https://stackoverflow.com/questions/64000916
复制相似问题