Skip to content

Instantly share code, notes, and snippets.

@ecordell
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ecordell/6134c6382028c6db09c5 to your computer and use it in GitHub Desktop.
Save ecordell/6134c6382028c6db09c5 to your computer and use it in GitHub Desktop.
Encrypted first party caveats
from pymacaroons import Macaroon, Verifier
from pymacaroons.field_encryptors import SecretBoxEncryptor
# Create a macaroon
m = Macaroon(
location='http://mybank/',
identifier='we used our secret key',
key='this is our super secret key; only we should know it'
)
# The encryptor has three elements:
# - a signifier ("sbe::" in this case) which is used to identify the encryption method
# when decrypting
# - a function encrypt(signature, field_data) which produces an encrypted field given the current
# signature and the data to encrypt
# - a function decrypt(signature, field_data) which decrypts the field given the current signature
# the data to decrypt
encryptor = SecretBoxEncryptor()
# You can also easily override the signifier with:
# encryptor = SecretBoxEncryptor(signifier='my-custom-enc::')
# or by creating your own FieldEncryptor
# Add a first party caveat along with a "field encryptor"
# which specifies the way in which a caveat should be encrypted
m.add_first_party_caveat('test = caveat', field_encryptor=encryptor)
# Notice that the caveat is encrypted, and an id "sbe::" has been prepended so
# that we know which method to use to decrypt it when verifying
print(m.inspect())
# location http://mybank/
# identifier we used our secret key
# cid sbe::a3ljErZSVwMgZlGHNpVI8jyMn5nsQOTCL/FdFWEFGLWG30lrJsI+Ecp6kQYqAKqzxg6obUQ=
# signature 574a6fca38ac1b93e259088c4b36850baea362dfa4e97bf7a2317310f5447ce2
# Let the verifier know that we expect at least one field to be decrypted with
# the SecretBoxEncryptor
v = Verifier(field_encryptors=[encryptor])
v.satisfy_exact('test = caveat')
verified = v.verify(
m,
'this is our super secret key; only we should know it'
)
# verified is True
# Example of a failing validation
v_bad = Verifier(field_encryptors=[encryptor])
v_bad.satisfy_exact('test != caveat')
verified = v_bad.verify(
m,
'this is our super secret key; only we should know it'
)
# Raises
# pymacaroons.exceptions.MacaroonUnmetCaveatException: Caveat not met.
# Unable to satisify: sbe::a3ljErZSVwMgZlGHNpVI8jyMn5nsQOTCL/FdFWEFGLWG30lrJsI+Ecp6kQYqAKqzxg6obUQ=
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment