publish-encrypted.py 1.3 KB

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