Skip to content

Instantly share code, notes, and snippets.

@dcwatson
Created July 22, 2020 05:15
Show Gist options
  • Save dcwatson/68ce00dd63b7e2f8fead3628d02cb14d to your computer and use it in GitHub Desktop.
Save dcwatson/68ce00dd63b7e2f8fead3628d02cb14d to your computer and use it in GitHub Desktop.
Basic Python implementation of CryptoKit's AES.GCM.SealedBox
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import binascii
import os
class SealedBox:
"""
Basic Python implementation of CryptoKit's AES.GCM.SealedBox
"""
@classmethod
def seal(cls, data, key, nonce=None):
if nonce is None:
nonce = os.urandom(12)
return nonce + AESGCM(key).encrypt(nonce, data, None)
@classmethod
def open(cls, data, key):
return AESGCM(key).decrypt(data[:12], data[12:], None)
if __name__ == "__main__":
# Round-trip test.
key = os.urandom(32)
assert SealedBox.open(SealedBox.seal(b"test", key), key) == b"test"
# These came from a CryptoKit playground.
box = binascii.unhexlify("18e6e51c4fd3ec17c731d1a62761a4609bf61beabbaa87cbe7a263566741adba166ab5b9955a39167d")
key = binascii.unhexlify("7c030ccb60a0f909259f4a2d9a2e3078cfe3c11d8357ead4a0cc6141593dd55b")
assert SealedBox.open(box, key) == b"Hello, world!"
@dcwatson
Copy link
Author

I don't, but I'm sure it was just generating a SymmetricKey and calling https://developer.apple.com/documentation/cryptokit/aes/gcm/3243033-seal (and dumping both using some kind of hex printing Data extension so I could easily check it in Python)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment