Repository: yt-dlp/yt-dlp
Issue category: Bug Report

Issue:
Bug in Native AES code causes chrome cookie extraction to fail
### DO NOT REMOVE OR SKIP THE ISSUE TEMPLATE

- [X] I understand that I will be **blocked** if I *intentionally* remove or skip any mandatory\* field

### Checklist

- [X] I'm reporting a bug unrelated to a specific site
- [X] I've verified that I have **updated yt-dlp to nightly or master** ([update instructions](https://github.com/yt-dlp/yt-dlp#update-channels))
- [X] I've checked that all provided URLs are playable in a browser with the same IP and same login details
- [X] I've checked that all URLs and arguments with special characters are [properly quoted or escaped](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#video-url-contains-an-ampersand--and-im-getting-some-strange-output-1-2839-or-v-is-not-recognized-as-an-internal-or-external-command)
- [X] I've searched [known issues](https://github.com/yt-dlp/yt-dlp/issues/3766) and the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues **including closed ones**. DO NOT post duplicates
- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)

### Provide a description that is worded well enough to be understood

The Native AES code has a bug causing chromium cookie decryption to fail. This affects yt-dlp installs without pycryptodomex, like the py2exe builds.

### Provide verbose output that clearly demonstrates the problem

- [X] Run **your** yt-dlp command with **-vU** flag added (`yt-dlp -vU <your command line>`)
- [ ] If using API, add `'verbose': True` to `YoutubeDL` params instead
- [X] Copy the WHOLE output (starting with `[debug] Command-line config`) and insert it below

### Complete Verbose Output

```shell
[debug] Command-line config: ['-v', '--cookies-from-browser', 'chromium']
[debug] Encodings: locale cp1252, fs utf-8, pref cp1252, out utf-8, error utf-8, screen utf-8
[debug] yt-dlp version nightly@2024.06.11.232712 from yt-dlp/yt-dlp-nightly-builds [add96eb9f] (pip)
[debug] Python 3.12.3 (CPython AMD64 64bit) - Windows-11-10.0.22631-SP0 (OpenSSL 3.0.13 30 Jan 2024)
[debug] exe versions: ffmpeg 7.0.1-full_build-www.gyan.dev (setts), ffprobe 7.0.1-full_build-www.gyan.dev, phantomjs 2.5.0, rtmpdump 2.4
[debug] Optional libraries: sqlite3-3.45.1
[debug] Proxy map: {}
Extracting cookies from chromium
[debug] Extracting cookies from: "C:\Users\User\AppData\Local\Chromium\User Data\Default\Network\Cookies"
[debug] Found local state file at "C:\Users\User\AppData\Local\Chromium\User Data\Local State"
[Cookies] Loading cookie      0/  3702WARNING: failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?
Extracted 3077 cookies from chromium (380 could not be decrypted)
[debug] cookie version breakdown: {'v10': 3592, 'other': 0, 'unencrypted': 110}
[debug] Request Handlers: urllib
[debug] Loaded 1820 extractors

Usage: __main__.py [OPTIONS] URL [URL...]

__main__.py: error: You must provide at least one URL.
Type yt-dlp --help to see a list of all options.
```



Hints:

Patch:
diff --git a/yt_dlp/aes.py b/yt_dlp/aes.py
index abf54a998e0e..be67b40fe215 100644
--- a/yt_dlp/aes.py
+++ b/yt_dlp/aes.py
@@ -230,11 +230,11 @@ def aes_gcm_decrypt_and_verify(data, key, tag, nonce):
     iv_ctr = inc(j0)
 
     decrypted_data = aes_ctr_decrypt(data, key, iv_ctr + [0] * (BLOCK_SIZE_BYTES - len(iv_ctr)))
-    pad_len = len(data) // 16 * 16
+    pad_len = (BLOCK_SIZE_BYTES - (len(data) % BLOCK_SIZE_BYTES)) % BLOCK_SIZE_BYTES
     s_tag = ghash(
         hash_subkey,
         data
-        + [0] * (BLOCK_SIZE_BYTES - len(data) + pad_len)        # pad
+        + [0] * pad_len                                         # pad
         + bytes_to_intlist((0 * 8).to_bytes(8, 'big')           # length of associated data
                            + ((len(data) * 8).to_bytes(8, 'big'))),  # length of data
     )


Test patch:
diff --git a/test/test_aes.py b/test/test_aes.py
index 5f975efecfa4..6fe6059a17ad 100644
--- a/test/test_aes.py
+++ b/test/test_aes.py
@@ -83,6 +83,18 @@ def test_gcm_decrypt(self):
                 data, intlist_to_bytes(self.key), authentication_tag, intlist_to_bytes(self.iv[:12]))
             self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg)
 
+    def test_gcm_aligned_decrypt(self):
+        data = b'\x159Y\xcf5eud\x90\x9c\x85&]\x14\x1d\x0f'
+        authentication_tag = b'\x08\xb1\x9d!&\x98\xd0\xeaRq\x90\xe6;\xb5]\xd8'
+
+        decrypted = intlist_to_bytes(aes_gcm_decrypt_and_verify(
+            list(data), self.key, list(authentication_tag), self.iv[:12]))
+        self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg[:16])
+        if Cryptodome.AES:
+            decrypted = aes_gcm_decrypt_and_verify_bytes(
+                data, bytes(self.key), authentication_tag, bytes(self.iv[:12]))
+            self.assertEqual(decrypted.rstrip(b'\x08'), self.secret_msg[:16])
+
     def test_decrypt_text(self):
         password = intlist_to_bytes(self.key).decode()
         encrypted = base64.b64encode(