1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-11-23 19:59:26 +01:00
ntfy/examples/publish-python/publish-encrypted.py

41 lines
1.3 KiB
Python
Raw Normal View History

2022-07-06 04:58:43 +02:00
#!/usr/bin/env python3
import requests
from base64 import b64encode, urlsafe_b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Hash import SHA256
from Crypto.Random import get_random_bytes
2022-07-08 14:16:03 +02:00
2022-07-06 04:58:43 +02:00
def derive_key(password, topic_url):
salt = SHA256.new(data=topic_url.encode('utf-8')).digest()
return PBKDF2(password, salt, 32, count=50000, hmac_hash_module=SHA256)
2022-07-08 14:16:03 +02:00
2022-07-06 04:58:43 +02:00
def encrypt(plaintext, key):
encoded_header = b64urlencode('{"alg":"dir","enc":"A256GCM"}'.encode('utf-8'))
2022-07-08 14:16:03 +02:00
iv = get_random_bytes(12) # GCM is used with a 96-bit IV
2022-07-06 04:58:43 +02:00
aad = encoded_header
cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
cipher.update(aad.encode('utf-8'))
ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode('utf-8'))
return "{header}..{iv}.{ciphertext}.{tag}".format(
2022-07-08 14:16:03 +02:00
header=encoded_header,
iv=b64urlencode(iv),
ciphertext=b64urlencode(ciphertext),
tag=b64urlencode(tag)
2022-07-06 04:58:43 +02:00
)
2022-07-08 14:16:03 +02:00
2022-07-06 04:58:43 +02:00
def b64urlencode(b):
return urlsafe_b64encode(b).decode('utf-8').replace("=", "")
2022-07-08 14:16:03 +02:00
2022-07-06 04:58:43 +02:00
key = derive_key("secr3t password", "https://ntfy.sh/mysecret")
ciphertext = encrypt('{"message":"Python says hi","tags":["secret"]}', key)
2022-07-08 14:16:03 +02:00
resp = requests.post("https://ntfy.sh/mysecret", data=ciphertext, headers={"Encryption": "jwe"})
2022-07-06 04:58:43 +02:00
resp.raise_for_status()