我正在尝试在Python中使用Chromium cookie,因为Chromium使用AES(与CBC)加密了它的cookie,所以我需要扭转这一情况。
我可以从OS X的Keychain(存储在Base 64中)中恢复AES密钥:
security find-generic-password -w -a Chrome -s Chrome Safe Storage
# From Python:
python -c 'from subprocess import PIPE, Popen; print(Popen(['security', 'find-generic-password', '-w', '-a', 'Chrome', '-s', 'Chrome Safe Storage'], stdout=PIPE).stdout.read().strip())'
这是我的代码,我所缺少的只是解密cookie:
from subprocess import PIPE, Popen
from sqlite3 import dbapi2
def get_encryption_key():
cmd = ['security', 'find-generic-password', '-w', '-a', 'Chrome', '-s', 'Chrome Safe Storage']
return Popen(cmd, stdout=PIPE).stdout.read().strip().decode('base-64')
def get_cookies(database):
key = get_encryption_key()
with dbapi2.connect(database) as conn:
conn.rollback()
rows = conn.cursor().execute('SELECT name, encrypted_value FROM cookies WHERE host_key like ".example.com"')
cookies = {}
for name, enc_val in rows:
val = decrypt(enc_val, key) # magic missing
cookies[name] = val
return cookies
我用pyCrypto的AES模块尝试了一堆东西,但是:
enc_val
长度不是16的倍数以下是一些似乎有用的链接:
你能帮我解决这个问题吗?
您在正确的轨道上!我已经为此工作了几天,终于弄清楚了。(非常感谢OP提供了到Chromium源的有用链接。)
我张贴了一篇文章,其中包含更多细节和有效脚本,但这是基本思想:
#! /usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
# Function to get rid of padding
def clean(x):
return x[:-x[-1]].decode('utf8')
# replace with your encrypted_value from sqlite3
encrypted_value = ENCRYPTED_VALUE
# Trim off the 'v10' that Chrome/ium prepends
encrypted_value = encrypted_value[3:]
# Default values used by both Chrome and Chromium in OSX and Linux
salt = b'saltysalt'
iv = b' ' * 16
length = 16
# On Mac, replace MY_PASS with your password from Keychain
# On Linux, replace MY_PASS with 'peanuts'
my_pass = MY_PASS
my_pass = my_pass.encode('utf8')
# 1003 on Mac, 1 on Linux
iterations = 1003
key = PBKDF2(my_pass, salt, length, iterations)
cipher = AES.new(key, AES.MODE_CBC, IV=iv)
decrypted = cipher.decrypt(encrypted_value)
print(clean(decrypted))