-
-
Save lavir/b5b16f95ae2fe5890b2a to your computer and use it in GitHub Desktop.
Implemented examples from https://docs.pushbullet.com/#end-to-end-encryption in python2/3 with python-cryptography (https://cryptography.io)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
from __future__ import unicode_literals | |
from binascii import a2b_base64, b2a_base64 | |
from cryptography.hazmat.primitives import hashes | |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives.ciphers import ( | |
Cipher, algorithms, modes | |
) | |
import os | |
def generate_key(): | |
password = b"hunter2" | |
salt = b"up0snaKOsn" | |
pkdf = PBKDF2HMAC( | |
algorithm=hashes.SHA256(), | |
length=32, | |
salt=salt, | |
iterations=30000, | |
backend=default_backend()) | |
key = pkdf.derive(password) | |
base64_key = b2a_base64(key) | |
print("base64_key:", base64_key) | |
def encrypt(): | |
key = a2b_base64("1sW28zp7CWv5TtGjlQpDHHG4Cbr9v36fG5o4f74LsKg=") | |
initialization_vector = os.urandom(12) | |
message = "meow!" | |
cipher = Cipher( | |
algorithms.AES(key), | |
modes.GCM(initialization_vector), | |
backend=default_backend() | |
).encryptor() | |
encrypted_message = cipher.update(message.encode()) + cipher.finalize() | |
# Must finalize encryption before getting tag | |
tag = cipher.tag | |
encoded_message = b"1" + tag + initialization_vector + encrypted_message | |
base64_encoded_message = b2a_base64(encoded_message) | |
print("base64_encoded_message:", base64_encoded_message) | |
def decrypt(): | |
key = a2b_base64("1sW28zp7CWv5TtGjlQpDHHG4Cbr9v36fG5o4f74LsKg=") | |
encoded_message = a2b_base64("MSfJxxY5YdjttlfUkCaKA57qU9SuCN8+ZhYg/xieI+lDnQ==") | |
version = encoded_message[0:1] | |
tag = encoded_message[1:17] | |
initialization_vector = encoded_message[17:29] | |
encrypted_message = encoded_message[29:] | |
if version != b"1": | |
raise Exception("Invalid Version") | |
decipher = Cipher( | |
algorithms.AES(key), | |
modes.GCM(initialization_vector, tag), | |
backend=default_backend() | |
).decryptor() | |
message = decipher.update(encrypted_message) + decipher.finalize() | |
message = message.decode() | |
print("message:", message) | |
if __name__ == "__main__": | |
generate_key() | |
encrypt() | |
decrypt() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment