title: Decrypting Chromium cookies
body: <p>I'm trying to use Chromium cookies in Python, because Chromium encrypts its cookies using AES (with CBC) I need to reverse this.</p>
  
  <p>I can recover the AES key from OS X's Keychain (it's stored in Base 64):</p>
  
  <pre><code>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())'
  </code></pre>
  
  <p>Here's the code I have, all I'm missing is decrypting the cookies:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I tried a bunch of things with <a href="http://pythonhosted.org/pycrypto/Crypto.Cipher.AES-module.html" rel="noreferrer">pyCrypto's AES module</a> but:</p>
  
  <ol>
  <li>I have no Initialization Vector (IV)</li>
  <li><code>enc_val</code> is not a multiple of 16 in length</li>
  </ol>
  
  <p>Here are some links that seem useful:</p>
  
  <ul>
  <li><a href="https://codereview.chromium.org/24734007" rel="noreferrer">the commit that started it all</a></li>
  <li><a href="https://src.chromium.org/viewvc/chrome/trunk/src/components/encryptor/keychain_password_mac.mm?pathrev=257572" rel="noreferrer">components/encryptor/keychain_password_mac.mm</a></li>
  <li><a href="https://src.chromium.org/viewvc/chrome/trunk/src/crypto/symmetric_key.h?revision=260152#l43" rel="noreferrer">AES key generation (not used in OS X but could help someone else)</a></li>
  <li><a href="https://src.chromium.org/viewvc/chrome/trunk/src/content/browser/net/sqlite_persistent_cookie_store.cc#l996" rel="noreferrer">cookie insertion function</a></li>
  </ul>
  
  <p>Can you help me figure this out?</p>