Skip to content

Instantly share code, notes, and snippets.

@tsangwpx
Created January 15, 2021 07:48
Show Gist options
  • Save tsangwpx/e9b8f060ce25b8d9ac0eba44813f42dc to your computer and use it in GitHub Desktop.
Save tsangwpx/e9b8f060ce25b8d9ac0eba44813f42dc to your computer and use it in GitHub Desktop.
from __future__ import annotations
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
=== REQUIREMENTS
pip install cryptography
=== USAGE
decrypted_data = decrypt_sticker_data(encrypted_data, pack_key_in_bytes)
"""
import hashlib
import hmac
from io import BytesIO
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CBC
from cryptography.hazmat.primitives.padding import PKCS7
# Size in bytes
HASH_OUTPUT_SIZE = 32 # sha256
BLOCK_SIZE = 16 # AES
CIPHER_KEY_SIZE = 32 # AES-256
MAC_KEY_SIZE = 32 # HMAC-SHA256
def hkdf(ikm: bytes, info: bytes, size: int, salt: bytes = None, variant=3):
"""simple key derivation function"""
if salt is None:
salt = bytes(HASH_OUTPUT_SIZE)
prk = hmac.digest(salt, ikm, 'sha256')
if variant == 3:
offset = 1
elif variant == 2:
offset = 0
else:
raise ValueError(f"Version = {variant}")
count = -(-size // HASH_OUTPUT_SIZE)
if info is None:
info = b''
mixin = b''
with BytesIO() as out:
for i in range(offset, offset + count):
mixin = hmac.digest(prk, mixin + info + bytes((i,)), 'sha256')
out.write(mixin)
return out.getvalue()[:size]
def split_bytes(x: bytes, size: int, size2: int):
"""Extract two fixed-sized bytes from a bytes"""
assert size >= 0 and size2 >= 0, (size, size2)
assert len(x) >= size + size2
return x[0:size], x[size:size + size2]
def verify_mac(data: bytes, mac: hmac.HMAC, their_digest: bytes = None):
digest = hashlib.sha256()
actual_data = data[:-digest.digest_size]
their_mac = data[-digest.digest_size:]
digest.update(actual_data)
mac.update(actual_data)
our_mac = mac.digest()
if not hmac.compare_digest(our_mac, their_mac):
raise ValueError('MAC')
digest.update(their_mac)
our_digest = digest.digest()
if their_digest is not None and not hmac.compare_digest(our_digest, their_digest):
raise ValueError('digest')
def decrypt_sticker_data(data: bytes, pack_key: bytes) -> bytes:
assert len(pack_key) == 32
okm = hkdf(pack_key, b'Sticker Pack', CIPHER_KEY_SIZE + MAC_KEY_SIZE)
part0, part1 = split_bytes(okm, CIPHER_KEY_SIZE, MAC_KEY_SIZE)
verify_mac(data, hmac.new(part1, None, 'sha256'), None)
iv, ciphertext = data[:BLOCK_SIZE], data[BLOCK_SIZE:-MAC_KEY_SIZE]
cipher = Cipher(AES(part0), CBC(iv))
decryptor = cipher.decryptor()
padded = decryptor.update(ciphertext) + decryptor.finalize()
unpadder = PKCS7(BLOCK_SIZE * 8).unpadder() # block size is in bits
unpadded = unpadder.update(padded) + unpadder.finalize()
return unpadded
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment