publish-encrypted.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python3
  2. import requests
  3. import json
  4. from base64 import b64encode, urlsafe_b64encode, b64decode
  5. from Crypto.Cipher import AES
  6. from Crypto.Random import get_random_bytes
  7. from Crypto.Protocol.KDF import PBKDF2
  8. from Crypto.Hash import SHA256
  9. from Crypto.Random import get_random_bytes
  10. def derive_key(password, topic_url):
  11. salt = SHA256.new(data=topic_url.encode('utf-8')).digest()
  12. return PBKDF2(password, salt, 32, count=50000, hmac_hash_module=SHA256)
  13. def encrypt(plaintext, key):
  14. encoded_header = b64urlencode('{"alg":"dir","enc":"A256GCM"}'.encode('utf-8'))
  15. iv = get_random_bytes(12) # GCM is used with a 96-bit IV
  16. aad = encoded_header
  17. cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
  18. cipher.update(aad.encode('utf-8'))
  19. ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode('utf-8'))
  20. return "{header}..{iv}.{ciphertext}.{tag}".format(
  21. header = encoded_header,
  22. iv = b64urlencode(iv),
  23. ciphertext = b64urlencode(ciphertext),
  24. tag = b64urlencode(tag)
  25. )
  26. def b64urlencode(b):
  27. return urlsafe_b64encode(b).decode('utf-8').replace("=", "")
  28. key = derive_key("secr3t password", "https://ntfy.sh/mysecret")
  29. ciphertext = encrypt('{"message":"Python says hi","tags":["secret"]}', key)
  30. resp = requests.post("https://ntfy.sh/mysecret",
  31. data=ciphertext,
  32. headers={
  33. "Encryption": "jwe"
  34. })
  35. resp.raise_for_status()