예제 #1
0
    def encrypt(self, data):
        json_data = compact_json(data)

        # create AES key
        # this key will be used later for decrypting the server's response
        self._key = Random.new().read(32)

        # encrypt data using AES key
        cipher = AES.new(self._key, AES.MODE_CTR)
        enc_data = cipher.encrypt(bytes(json_data, encoding="UTF-8"))

        # encrypt AES key using server's public RSA key
        encryptor = PKCS1_OAEP.new(self._public_rsa_key)
        enc_key = encryptor.encrypt(self._key)

        # convert to base 64 characters (so json can parse)
        b64_enc_data = b64encode(enc_data).decode()
        b64_enc_key = b64encode(enc_key).decode()
        b64_nonce = b64encode(cipher.nonce).decode()

        # return encrypted AES key, nonce value, and encrypted data
        # only the server can decrypt the encryped AES key
        # nonce is required for decryption since it works as a salt
        # nonce is used for stopping replay attacks
        return [b64_enc_key, b64_nonce], b64_enc_data
예제 #2
0
    def encrypt(self, key, data):
        data = compact_json(data)
        cipher = AES.new(key, AES.MODE_CTR)
        enc_data = cipher.encrypt(bytes(data, encoding="UTF-8"))

        b64_enc_data = b64encode(enc_data).decode()
        b64_nonce = b64encode(cipher.nonce).decode()

        return b64_nonce, b64_enc_data
예제 #3
0
    def _create_encryption_layer(self, request):
        if self._encryption_handler:
            json_request = compact_json(request)
            encryption_layer = [
                True, *self._encryption_handler.encrypt(json_request)
            ]
        else:
            encryption_layer = [False, request]

        return encryption_layer
예제 #4
0
 def _send(self, connection, data):
     data = compact_json(data)
     connection.sendall(data.encode("UTF-8"))
예제 #5
0
 def _send(self, soc, request):
     message = compact_json(request)
     soc.sendall(message.encode("UTF-8"))