def dump_resource(request): arch_pubkey = getattr(request.registry, 'arch_pubkey', None) res_secretkey = SecretKey() archive_box = Box(res_secretkey, arch_pubkey) res_pubkey = res_secretkey.pk del res_secretkey data = request.context.serialize() json_data = dumps(data) encrypted_data = archive_box.encrypt(json_data) return {'item': b64encode(encrypted_data), 'pubkey': b64encode(res_pubkey)}
def testBoxing(): msg = b'Hey there, a msg for you' # Generate the key pairs for Alice and bob, if secret keys already exist # they can be passed in, otherwise new keys will be automatically generated bob = SecretKey() alice = SecretKey() """ Alice: aA (a is alices private key, A is Alice's public key) A = G*a Bob: bB B = G*b hash(a*B) == hash(b*A) : hypothesis hash(a*G*b) == hash(b*G*a) : substitution hash(G*a*b) == hash(G*a*b) : commutative property of ECC math True! """ # Create the boxes, this is an object which represents the combination of the # sender's secret key and the receiver's public key bob_box = Box(bob.sk, alice.pk) alice_box = Box(alice.sk, bob.pk) # Bob's box encrypts messages for Alice bob_ctxt = bob_box.encrypt(msg) # Alice's box decrypts messages from Bob bclear = alice_box.decrypt(bob_ctxt) # Alice can send encrypted messages which only Bob can decrypt alice_ctxt = alice_box.encrypt(msg) aclear = bob_box.decrypt(alice_ctxt) print(bob.for_json()) print("bob's public key" + bob.hex_pk().hex()) print("bob's secret key" + bob.hex_sk().hex())
class CryptoBox(): def __init__(self, keyobj): self.keyobj = keyobj self.box = None def box_with(self, peer_pk): # create a box with peer_pk (in pk bin format) self.box = Box(self.keyobj.sk, peer_pk) def encrypt(self, msg): return self.box.encrypt(msg) def decrypt(self, msg): return self.box.decrypt(msg)
def box_encrypt(content: bytes, secret_key: SecretKey, public_key: PublicKey) -> EncryptedBox: ''' Encrypt the content for the public_key using the secret_key. ''' if secret_key is None: raise ValueError("secret_key may not be None") if public_key is None: raise ValueError("public_key may not be None") if isinstance(public_key, bytes): public_key = libnacl.public.PublicKey(public_key) if isinstance(secret_key, bytes): secret_key = libnacl.public.SecretKey(secret_key) box = Box(sk=secret_key, pk=public_key) # Encrypt messages nonce, data = box.encrypt(content, pack_nonce=False) return EncryptedBox(nonce=nonce, data=data)