Skip to content

Instantly share code, notes, and snippets.

@DC3
Last active October 19, 2023 06:25
Show Gist options
  • Save DC3/77145758edeaa158c870f1dd6dc4f631 to your computer and use it in GitHub Desktop.
Save DC3/77145758edeaa158c870f1dd6dc4f631 to your computer and use it in GitHub Desktop.
Bun + js decrypt chromium sqlite cookie
// TODO v11 v12
import { Database } from 'bun:sqlite'
import { createDecipheriv, pbkdf2Sync } from 'node:crypto'
const KEY_LENGTH = 16
const SALT = 'saltysalt'
const IV = Buffer.alloc(KEY_LENGTH).fill(' ')
const password = 'peanuts'
const key = getDerivedKey(password, 1)
function getDerivedKey(password, iterations) {
return pbkdf2Sync(password, SALT, iterations, KEY_LENGTH, 'sha1')
}
function decryptorCookie(encryptedCookie) {
const decipher = createDecipheriv('AES-128-CBC', key, IV)
const decryptedCookie = decipher.update(encryptedCookie.slice(3))
return decryptedCookie.toString() + decipher.final('utf8')
}
function parseExpiresUtc(n) {
return new Date(n / 1e3 - 116444736e5)
}
function parseCookie(item) {
const { name, host_key, encrypted_value: str, expires_utc, has_expires } = item
// V10
const val = decryptorCookie(str)
const expires = parseExpiresUtc(expires_utc)
const unixTime = +(expires / 1e3).toFixed(0)
const out = { key: name, val, has_expires, expires, host: host_key, unixTime }
return out
}
const DefaultDbPath = '~/.config/chromium/Default/Cookies'
export function getCookies(sql, dbPath = DefaultDbPath) {
const db = new Database(dbPath)
const query = db.query(sql)
const items = query.all()
return items.map(parseCookie)
}
export function toNetscapeCookieFile(arr) {
const lines = arr
.map(c => {
return `${c.host} TRUE / TRUE ${c.unixTime} ${c.key} ${c.val}`
})
.join('\n')
return `# Netscape HTTP Cookie File
# This file is generated by yt-dlp. Do not edit.
${lines}`
}
export function toHeadersCookie(arr) {
return arr.map(c => `${c.key}=${c.val}`).join('; ')
}
if (import.meta.main) {
const sql = `SELECT * FROM cookies where host_key = '.aliyundrive.com' and name = 'cookie2';`
console.log(getCookies(sql))
const sql1 = `SELECT * FROM cookies where host_key = '.bilibili.com' and name = 'SESSDATA';`
const cookies = await getCookies(sql1)
console.log(toNetscapeCookieFile(cookies))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment