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)}
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 setUpClass(cls): cls.config = testing.setUp() cls.config.add_renderer('jsonp', JSONP(param_name='callback')) cls.config.include("cornice") cls.authz_policy = ACLAuthorizationPolicy() cls.authn_policy = AuthenticationPolicy( "{}/auth.ini".format(os.path.dirname(os.path.abspath(__file__))), __name__) cls.config.set_authorization_policy(cls.authz_policy) cls.config.set_authentication_policy(cls.authn_policy) cls.config.registry.db = MagicMock() cls.config.registry.db.save.return_value = [ '', '1-{}'.format(uuid.uuid4().hex) ] cls.config.registry.server_id = uuid.uuid4().hex cls.config.registry.docservice_key = MagicMock() cls.config.context = munchify(tender.serialize.return_value) cls.config.registry.decr_box = Box("b" * 32, "c" * 32) cls.config.add_subscriber(add_logging_context, NewRequest) cls.config.add_subscriber(MagicMock(), ContextFound) cls.config.add_subscriber(MagicMock(), NewRequest) cls.config.add_subscriber(MagicMock(), BeforeRender) cls.config.scan("openprocurement.archivarius.core.tests.utils") cls.app = TestApp(CatchErrors(cls.config.make_wsgi_app()))
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)
def test_dump_resource(self, mock_crypto_box_keypair): request = MagicMock() request.registry.arch_pubkey = 'c' * 32 mock_crypto_box_keypair.return_value = ["a" * 32, "b" * 32] context = { 'id': uuid.uuid4().hex, 'rev': '1-{}'.format(uuid.uuid4().hex), 'dateModified': datetime.now().isoformat(), 'doc_type': 'Tenders' } request.context.serialize.return_value = context dump = dump_resource(request) res, key = dump['item'], dump['pubkey'] decrypt_box = Box("b" * 32, "c" * 32) decrypted_data = decrypt_box.decrypt(b64decode(res)) decrypted_data = json.loads(decrypted_data) self.assertNotEqual(res, json.dumps(context)) self.assertEqual(decrypted_data, context)
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())
def box_with(self, peer_pk): # create a box with peer_pk (in pk bin format) self.box = Box(self.keyobj.sk, peer_pk)