diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3f26cfa7b9e632a2f184129225ac24f86a4836a6..0b072499dfa18090c990b1b3804efc203f8fe8e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file.
 
 #### Changed
 - Use translation  for privacy policy document block on consent screen from module Perun
+- Connection to the database obtained through the SimpleSAML Database class
 
 #### Fixed
 - Fixed bad check in NagiosStatusConnector.php
diff --git a/hooks/hook_cron.php b/hooks/hook_cron.php
index 081159cc328593980f423f767052d2e1fa1fbf56..ffa4b1e4fb94a046ae5fbfda142bba29a212dd54 100644
--- a/hooks/hook_cron.php
+++ b/hooks/hook_cron.php
@@ -1,10 +1,7 @@
 <?php
 
 use SimpleSAML\Logger;
-use SimpleSAML\Module\perun\DatabaseConnector;
-
-const TABLE_NAME = 'scriptChallenges';
-const DATE_COLUMN = 'date';
+use SimpleSAML\Module\perun\databaseCommand\ChallengesDbCmd;
 
 /**
  * Hook to run a cron job.
@@ -18,34 +15,11 @@ function challenges_hook_cron(&$croninfo)
         Logger::debug('cron [perun]: Skipping cron in cron tag [' . $croninfo['tag'] . '] ');
         return;
     }
-
     Logger::info('cron [perun]: Running cron in cron tag [' . $croninfo['tag'] . '] ');
 
-    try {
-        $databaseConnector = new DatabaseConnector();
-        $conn = $databaseConnector->getConnection();
-
-        if ($conn !== null) {
-            $stmt = $conn->prepare(
-                'DELETE FROM ' . TABLE_NAME . ' WHERE ' . DATE_COLUMN . ' < (NOW() - INTERVAL 5 MINUTE)'
-            );
-
-            if (!$stmt) {
-                $conn->close();
-                Logger::error('cron [perun]: Error during preparing statement');
-                return;
-            }
-
-            $ex = $stmt->execute();
-
-            if ($ex === false) {
-                Logger::error('cron [perun]: Error while deleting old challenges from the database.');
-            }
+    $challengesDbCmd = new ChallengesDbCmd();
 
-            $stmt->close();
-            $conn->close();
-        }
-    } catch (\Exception $e) {
-        $croninfo['summary'][] = 'Error while deleting old challenges from the database: ' . $e->getMessage();
+    if (!$challengesDbCmd->deleteOldChallenges()) {
+        Logger::error('cron [perun]: Error while deleting old challenges from the database.');
     }
 }
diff --git a/lib/ChallengeManager.php b/lib/ChallengeManager.php
new file mode 100644
index 0000000000000000000000000000000000000000..c3bf57dbd2399da2f08440dc5e841373174c8ee7
--- /dev/null
+++ b/lib/ChallengeManager.php
@@ -0,0 +1,79 @@
+<?php
+
+namespace SimpleSAML\Module\perun;
+
+use SimpleSAML\Logger;
+use SimpleSAML\Module\perun\databaseCommand\ChallengesDbCmd;
+
+class ChallengeManager
+{
+    const LOG_PREFIX = 'Perun:ChallengeManager: ';
+    private $challengeDbCmd;
+
+    public function __construct()
+    {
+        $this->challengeDbCmd = new ChallengesDbCmd();
+    }
+
+    public function insertChallenge($challenge, $id, $scriptName): bool
+    {
+        if (empty($challenge) ||
+            empty($id) ||
+            empty($scriptName) ||
+            !$this->challengeDbCmd->insertChallenge($challenge, $id, $scriptName)) {
+            Logger::error(self::LOG_PREFIX . 'Error while creating a challenge');
+            http_response_code(500);
+            return false;
+        }
+
+        return true;
+    }
+
+    public function readChallengeFromDb($id)
+    {
+        if (empty($id)) {
+            http_response_code(400);
+            return null;
+        }
+
+        $result = $this->challengeDbCmd->readChallenge($id);
+
+        if ($result === null) {
+            http_response_code(500);
+        }
+
+        return $result;
+    }
+
+    public static function checkAccess($challenge, $challengeDb): bool
+    {
+        if (empty($challenge) || empty($challengeDb)) {
+            http_response_code(400);
+            return false;
+        }
+
+        if (!hash_equals($challengeDb, $challenge)) {
+            Logger::error(self::LOG_PREFIX . 'Hashes are not equal.');
+            http_response_code(401);
+            return false;
+        }
+
+        return true;
+    }
+
+    public function deleteChallengeFromDb($id): bool
+    {
+        if (empty($id)) {
+            http_response_code(400);
+            return false;
+        }
+
+        if (!$this->challengeDbCmd->deleteChallenge($id)) {
+            Logger::error(self::LOG_PREFIX . 'Error while deleting challenge from the database.');
+            http_response_code(500);
+            return false;
+        }
+
+        return true;
+    }
+}
diff --git a/lib/DatabaseCommand.php b/lib/DatabaseCommand.php
deleted file mode 100644
index fe6c40c638671b00e22ec83213d4777cca4c17f6..0000000000000000000000000000000000000000
--- a/lib/DatabaseCommand.php
+++ /dev/null
@@ -1,183 +0,0 @@
-<?php
-
-namespace SimpleSAML\Module\perun;
-
-use SimpleSAML\Logger;
-
-/**
- * Class for working with Database
- *
- * @author Pavel VyskoÄŤil <vyskocilpavel@muni.cz>
- */
-class DatabaseCommand
-{
-
-    const WHITELIST = 'whiteList';
-    const GREYLIST = 'greyList';
-    /**
-     * Function returns array of all IdPs in whitelist/greylist
-     * @param string $tableName 'whitelist' or 'greylist'
-     * @return array of all IdPs, every IdP is represents as array
-     */
-    public static function getAllIdps($tableName)
-    {
-        $databaseConnector = new DatabaseConnector();
-        $conn = $databaseConnector->getConnection();
-        $whiteListTableName = $databaseConnector->getWhiteListTableName();
-        $greyListTableName = $databaseConnector->getGreyListTableName();
-        $table = null;
-        $listOfIdPs = [];
-        assert($conn !== null);
-
-        if ($tableName === self::WHITELIST) {
-            $table = $whiteListTableName;
-        } elseif ($tableName === self::GREYLIST) {
-            $table = $greyListTableName;
-        }
-
-        $stmt = $conn->prepare('SELECT * FROM ' . $table);
-
-        if ($stmt) {
-            $ex = $stmt->execute();
-            if ($ex === false) {
-                Logger::error('Error during select all from ' . $table);
-            }
-
-            $stmt->bind_result($timestamp, $entityId, $reason);
-            while ($stmt->fetch()) {
-                $idp = [];
-                $idp['timestamp'] = $timestamp;
-                $idp['entityid'] = $entityId;
-                $idp['reason'] = $reason;
-                array_push($listOfIdPs, $idp);
-            }
-
-            $stmt->close();
-        } else {
-            Logger::error('Error during preparing statement');
-        }
-
-        $conn->close();
-        return $listOfIdPs;
-    }
-
-    /**
-     * Function returns array of all entityId in whitelist/greylist
-     * @param string $tableName 'whitelist' or 'greylist'
-     * @return array of entityIds
-     */
-    public static function getAllEntityIds($tableName)
-    {
-        $databaseConnector = new DatabaseConnector();
-        $conn = $databaseConnector->getConnection();
-        $whiteListTableName = $databaseConnector->getWhiteListTableName();
-        $greyListTableName = $databaseConnector->getGreyListTableName();
-        $table = null;
-        $listOfIdPs = [];
-        assert($conn !== null);
-
-        if ($tableName === self::WHITELIST) {
-            $table = $whiteListTableName;
-        } elseif ($tableName === self::GREYLIST) {
-            $table = $greyListTableName;
-        }
-
-        $stmt = $conn->prepare("SELECT * FROM " . $table);
-
-        if ($stmt) {
-            $ex = $stmt->execute();
-            if ($ex === false) {
-                Logger::error('Error during select all entityIds from ' . $table);
-            }
-
-            $stmt->bind_result($timestamp, $entityId, $reason);
-            while ($stmt->fetch()) {
-                array_push($listOfIdPs, $entityId);
-            }
-
-            $stmt->close();
-        } else {
-            Logger::error('Error during preparing statement');
-        }
-
-        $conn->close();
-        return $listOfIdPs;
-    }
-
-    /**
-     * Function inserts the line into table with $tableName
-     * @param string $tableName 'whitelist' or 'greylist'
-     * @param string $entityId
-     * @param string $reason
-     */
-    public static function insertTolist($tableName, $entityId, $reason)
-    {
-        $databaseConnector = new DatabaseConnector();
-        $conn = $databaseConnector->getConnection();
-        $whiteListTableName = $databaseConnector->getWhiteListTableName();
-        $greyListTableName = $databaseConnector->getGreyListTableName();
-        $table = null;
-        assert($conn !== null);
-
-        if ($tableName === self::WHITELIST) {
-            $table = $whiteListTableName;
-        } elseif ($tableName === self::GREYLIST) {
-            $table = $greyListTableName;
-        }
-
-        $stmt = $conn->prepare('INSERT INTO ' . $table . ' (entityId, reason) VALUES (?, ?)');
-
-        if ($stmt) {
-            $stmt->bind_param('ss', $entityId, $reason);
-            $ex = $stmt->execute();
-            if ($ex === false) {
-                Logger::error('Error during inserting entityId ' . $entityId . ' into ' . $table);
-            }
-
-            Logger::debug('EntityId ' . $entityId . ' was inserted into ' . $table);
-            $stmt->close();
-        } else {
-            Logger::error('Error during preparing statement');
-        }
-
-        $conn->close();
-    }
-
-    /**
-     * Function deletes the line from table with $tableName and $entityID
-     * @param string $tableName 'whitelist' or 'greylist'
-     * @param string $entityId
-     */
-    public static function deleteFromList($tableName, $entityId)
-    {
-        $databaseConnector = new DatabaseConnector();
-        $conn = $databaseConnector->getConnection();
-        $whiteListTableName = $databaseConnector->getWhiteListTableName();
-        $greyListTableName = $databaseConnector->getGreyListTableName();
-        $table = null;
-        assert($conn !== null);
-
-        if ($tableName === self::WHITELIST) {
-            $table = $whiteListTableName;
-        } elseif ($tableName === self::GREYLIST) {
-            $table = $greyListTableName;
-        }
-
-        $stmt = $conn->prepare("DELETE FROM " . $table . " WHERE entityId=?");
-
-        if ($stmt) {
-            $stmt->bind_param('s', $entityId);
-            $ex = $stmt->execute();
-            if ($ex === false) {
-                Logger::error('Error during deleting entityId ' . $entityId . ' from ' . $table);
-            }
-
-            Logger::debug('EntityId ' . $entityId . ' was deleted from ' . $table);
-            $stmt->close();
-        } else {
-            Logger::error('Error during preparing statement');
-        }
-
-        $conn->close();
-    }
-}
diff --git a/lib/DatabaseConnector.php b/lib/DatabaseConnector.php
deleted file mode 100644
index ad89c7c1e1ececd17e80d63da620c2d99bfe0b23..0000000000000000000000000000000000000000
--- a/lib/DatabaseConnector.php
+++ /dev/null
@@ -1,113 +0,0 @@
-<?php
-
-namespace SimpleSAML\Module\perun;
-
-use SimpleSAML\Configuration;
-use SimpleSAML\Logger;
-
-/**
- * Class for getting connection to DB
- *
- * @author Pavel VyskoÄŤil <vyskocilpavel@muni.cz>
- */
-class DatabaseConnector
-{
-    private $serverName;
-    private $port;
-    private $username;
-    private $password;
-    private $databaseName;
-    private $whitelistTableName;
-    private $greyListTableName;
-    private $encryption;
-    private $sslCA;
-    private $sslCert;
-    private $sslKey;
-    private $sslCAPath;
-
-    const CONFIG_FILE_NAME = 'module_perun_idpListsServiceDB.php';
-    const SERVER = 'serverName';
-    const PORT = 'port';
-    const USER = 'userName';
-    const PASSWORD = 'password';
-    const DATABASE = 'databaseName';
-    const WHITELIST_TABLE_NAME = 'whiteListTableName';
-    const GREYLIST_TABLE_NAME = 'greyListTableName';
-    const ENCRYPTION = 'encryption';
-    const SSL_CA = 'ssl_ca';
-    const SSL_CERT = 'ssl_cert_path';
-    const SSL_KEY = 'ssl_key_path';
-    const SSL_CA_PATH = 'ssl_ca_path';
-
-    public function __construct()
-    {
-        $conf = Configuration::getConfig(self::CONFIG_FILE_NAME);
-        $this->serverName = $conf->getString(self::SERVER);
-        $this->port = $conf->getInteger(self::PORT, null);
-        $this->username = $conf->getString(self::USER);
-        $this->password = $conf->getString(self::PASSWORD);
-        $this->databaseName = $conf->getString(self::DATABASE);
-        $this->whitelistTableName = $conf->getString(self::WHITELIST_TABLE_NAME);
-        $this->greyListTableName = $conf->getString(self::GREYLIST_TABLE_NAME);
-        $this->encryption = $conf->getBoolean(self::ENCRYPTION);
-        $this->sslCA = $conf->getString(self::SSL_CA);
-        $this->sslCert = $conf->getString(self::SSL_CERT);
-        $this->sslKey = $conf->getString(self::SSL_KEY);
-        $this->sslCAPath = $conf->getString(self::SSL_CA_PATH);
-    }
-
-    /**
-     * Function returns the connection to db
-     * @return mysqli connection
-     */
-    public function getConnection()
-    {
-        $conn = mysqli_init();
-        if ($this->encryption === true) {
-            Logger::debug('Getting connection with encryption.');
-            mysqli_ssl_set($conn, $this->sslKey, $this->sslCert, $this->sslCA, $this->sslCAPath, null);
-            if ($this->port === null) {
-                mysqli_real_connect($conn, $this->serverName, $this->username, $this->password, $this->databaseName);
-            } else {
-                mysqli_real_connect(
-                    $conn,
-                    $this->serverName,
-                    $this->username,
-                    $this->password,
-                    $this->databaseName,
-                    $this->port
-                );
-            }
-        } elseif ($this->port === null) {
-            mysqli_real_connect($conn, $this->serverName, $this->username, $this->password, $this->databaseName);
-        } else {
-            mysqli_real_connect(
-                $conn,
-                $this->serverName,
-                $this->username,
-                $this->password,
-                $this->databaseName,
-                $this->port
-            );
-        }
-        return $conn;
-    }
-
-    /**
-     * Function returns name of table for whitelist
-     * @return mixed whitelist table name
-     */
-    public function getWhiteListTableName()
-    {
-        return $this->whitelistTableName;
-    }
-
-    /**
-     * Function returns name of table for greylist
-     * @return mixed whitelist table name
-     */
-    public function getGreyListTableName()
-    {
-        return $this->greyListTableName;
-    }
-}
diff --git a/lib/IdpListsServiceDB.php b/lib/IdpListsServiceDB.php
index d8ef047ee8d923462205084ca7a4c6389885eb32..457e3313baa1bd81b4244920123601fe954653c5 100644
--- a/lib/IdpListsServiceDB.php
+++ b/lib/IdpListsServiceDB.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\perun;
 
+use SimpleSAML\Module\perun\databaseCommand\IdpListsServiceDbCmd;
+
 /**
  * Implementation of IdpListsService using DB
  *
@@ -9,25 +11,31 @@ namespace SimpleSAML\Module\perun;
  */
 class IdpListsServiceDB extends IdpListsService
 {
+    private $idpListServiceDbCmd;
+
+    public function __construct()
+    {
+        $this->idpListServiceDbCmd = new IdpListsServiceDbCmd();
+    }
 
     public function getWhitelist()
     {
-        return DatabaseCommand::getAllIdps(DatabaseCommand::WHITELIST);
+        return $this->idpListServiceDbCmd->getAllIdps($this->idpListServiceDbCmd::WHITELIST);
     }
 
     public function getGreylist()
     {
-        return DatabaseCommand::getAllIdps(DatabaseCommand::GREYLIST);
+        return $this->idpListServiceDbCmd->getAllIdps($this->idpListServiceDbCmd::GREYLIST);
     }
 
     public function getWhitelistEntityIds()
     {
-        return DatabaseCommand::getAllEntityIds(DatabaseCommand::WHITELIST);
+        return $this->idpListServiceDbCmd->getAllEntityIds($this->idpListServiceDbCmd::WHITELIST);
     }
 
     public function getGreylistEntityIds()
     {
-        return DatabaseCommand::getAllEntityIds(DatabaseCommand::GREYLIST);
+        return $this->idpListServiceDbCmd->getAllEntityIds($this->idpListServiceDbCmd::GREYLIST);
     }
 
     public function isWhitelisted($entityID)
@@ -43,9 +51,9 @@ class IdpListsServiceDB extends IdpListsService
     public function whitelistIdp($entityID, $reason = null)
     {
         if (!$this->isWhitelisted($entityID)) {
-            DatabaseCommand::insertTolist(DatabaseCommand::WHITELIST, $entityID, $reason);
+            $this->idpListServiceDbCmd->insertToList($this->idpListServiceDbCmd::WHITELIST, $entityID, $reason);
             if ($this->isGreylisted($entityID)) {
-                DatabaseCommand::deleteFromList(DatabaseCommand::GREYLIST, $entityID);
+                $this->idpListServiceDbCmd->deleteFromList($this->idpListServiceDbCmd::GREYLIST, $entityID);
             }
         }
     }
diff --git a/lib/ScriptsUtils.php b/lib/ScriptsUtils.php
deleted file mode 100644
index 4bc1547ea87d16eb9d8444566c28e5bfd0cfe5eb..0000000000000000000000000000000000000000
--- a/lib/ScriptsUtils.php
+++ /dev/null
@@ -1,133 +0,0 @@
-<?php
-
-
-namespace SimpleSAML\Module\perun;
-
-
-class ScriptsUtils
-{
-    const CHALLENGES_TABLE_NAME = 'scriptChallenges';
-    const CHALLENGE = 'challenge';
-
-    public static function generateChallenge($connection, $challenge, $id, $scriptName): bool
-    {
-        if ($connection === null || empty($challenge)) {
-            Logger::error('Perun:ScriptsUtils: Error while creating a challenge');
-            http_response_code(500);
-            return false;
-        }
-
-        $stmt = $connection->prepare(
-            'INSERT INTO ' . self::CHALLENGES_TABLE_NAME . ' (id, challenge, script) VALUES (?, ?, ?)'
-        );
-
-        if ($stmt) {
-            $stmt->bind_param('sss', $id, $challenge, $scriptName);
-            $ex = $stmt->execute();
-
-            if ($ex === false) {
-                Logger::error('Perun:ScriptsUtils: Error while creating a challenge');
-                http_response_code(500);
-                return false;
-            }
-
-            $stmt->close();
-        } else {
-            Logger::error('Perun:ScriptsUtils: Error during preparing statement');
-            http_response_code(500);
-            return false;
-        }
-
-        return true;
-    }
-
-    public static function readChallengeFromDb($connection, $id)
-    {
-        if ($connection === null) {
-            http_response_code(500);
-            return null;
-        }
-
-        if (empty($id)) {
-            http_response_code(400);
-            return null;
-        }
-
-        $stmt = $connection->prepare('SELECT challenge FROM ' . self::CHALLENGES_TABLE_NAME . ' WHERE id=?');
-
-        if (!$stmt) {
-            Logger::error('Perun:ScriptsUtils: Error during preparing statement');
-            http_response_code(500);
-            return null;
-        }
-
-        $stmt->bind_param('s', $id);
-        $ex = $stmt->execute();
-
-        if ($ex === false) {
-            Logger::error('Perun:ScriptsUtils: Error while getting the challenge from the database.');
-            http_response_code(500);
-            return null;
-        }
-
-        $challengeDb = $stmt->get_result()->fetch_assoc()[self::CHALLENGE];
-        $stmt->close();
-
-        return $challengeDb;
-    }
-
-    public static function checkAccess($connection, $challenge, $challengeDb): bool
-    {
-        if ($connection === null) {
-            http_response_code(500);
-            return false;
-        }
-
-        if (empty($challenge) || empty($challengeDb)) {
-            http_response_code(400);
-            return false;
-        }
-
-        if (!hash_equals($challengeDb, $challenge)) {
-            Logger::error('Perun:ScriptsUtils: Hashes are not equal.');
-            http_response_code(401);
-            return false;
-        }
-
-        return true;
-    }
-
-    public static function deleteChallengeFromDb($connection, $id): bool
-    {
-        if ($connection === null) {
-            http_response_code(500);
-            return false;
-        }
-
-        if (empty($id)) {
-            http_response_code(400);
-            return false;
-        }
-
-        $stmt = $connection->prepare('DELETE FROM ' . self::CHALLENGES_TABLE_NAME . ' WHERE id=?');
-
-        if ($stmt) {
-            $stmt->bind_param('s', $id);
-            $ex = $stmt->execute();
-
-            if ($ex === false) {
-                Logger::error('Perun:ScriptsUtils: Error while deleting the challenge from the database.');
-                http_response_code(500);
-                return false;
-            }
-
-            $stmt->close();
-        } else {
-            Logger::error('Perun:ScriptsUtils: Error during preparing statement');
-            http_response_code(500);
-            return false;
-        }
-
-        return true;
-    }
-}
diff --git a/lib/databaseCommand/ChallengesDbCmd.php b/lib/databaseCommand/ChallengesDbCmd.php
new file mode 100644
index 0000000000000000000000000000000000000000..acbf3a1a6e86b85ace07c18fc9029dd0703f1470
--- /dev/null
+++ b/lib/databaseCommand/ChallengesDbCmd.php
@@ -0,0 +1,68 @@
+<?php
+
+namespace SimpleSAML\Module\perun\databaseCommand;
+
+/**
+ * @author Dominik Baranek <baranek@ics.muni.cz>
+ */
+class ChallengesDbCmd extends DatabaseCommand
+{
+    const CHALLENGES_TABLE_NAME = 'scriptChallenges';
+    const ID_COLUMN = 'id';
+    const CHALLENGE_COLUMN = 'challenge';
+    const SCRIPT_COLUMN = 'script';
+    const DATE_COLUMN = 'date';
+
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    public function insertChallenge($challenge, $id, $scriptName): bool
+    {
+        $query = 'INSERT INTO ' . self::CHALLENGES_TABLE_NAME .
+            ' (' . self::ID_COLUMN . ', ' . self::CHALLENGE_COLUMN . ', ' . self::SCRIPT_COLUMN . ') VALUES' .
+            ' (:' . self::ID_COLUMN . ', :' . self::CHALLENGE_COLUMN . ', :' . self::SCRIPT_COLUMN . ')';
+
+        $params = [
+            self::ID_COLUMN => $id,
+            self::CHALLENGE_COLUMN => $challenge,
+            self::SCRIPT_COLUMN => $scriptName
+        ];
+
+        return $this->write($query, $params);
+    }
+
+    public function readChallenge($id)
+    {
+        $query = 'SELECT challenge FROM ' . self::CHALLENGES_TABLE_NAME . ' WHERE ' .
+            self::ID_COLUMN . ' = :' . self::ID_COLUMN;
+
+        $params = [
+            self::ID_COLUMN => $id
+        ];
+
+        return $this->read($query, $params)->fetchColumn();
+    }
+
+    public function deleteChallenge($id): bool
+    {
+        $query = 'DELETE FROM ' . self::CHALLENGES_TABLE_NAME . ' WHERE ' . self::ID_COLUMN . ' = :' . self::ID_COLUMN;
+
+        $params = [
+            self::ID_COLUMN => $id
+        ];
+
+        return $this->write($query, $params);
+    }
+
+    public function deleteOldChallenges(): bool
+    {
+        $query = 'DELETE FROM ' . self::CHALLENGES_TABLE_NAME . ' WHERE '
+            . self::DATE_COLUMN . ' < (NOW() - INTERVAL 5 MINUTE)';
+
+        $params = [];
+
+        return $this->write($query, $params);
+    }
+}
diff --git a/lib/databaseCommand/DatabaseCommand.php b/lib/databaseCommand/DatabaseCommand.php
new file mode 100644
index 0000000000000000000000000000000000000000..74e6368b1e561801876548e200ee66303f3e8a8e
--- /dev/null
+++ b/lib/databaseCommand/DatabaseCommand.php
@@ -0,0 +1,31 @@
+<?php
+
+namespace SimpleSAML\Module\perun\databaseCommand;
+
+use SimpleSAML\Database;
+
+/**
+ * @author Dominik Baranek <baranek@ics.muni.cz>
+ */
+abstract class DatabaseCommand
+{
+    protected $config;
+
+    private $conn;
+
+    public function __construct()
+    {
+        $this->config = DatabaseConfig::getInstance();
+        $this->conn = Database::getInstance($this->config->getStore());
+    }
+
+    protected function read($query, $params)
+    {
+        return $this->conn->read($query, $params);
+    }
+
+    protected function write($query, $params): bool
+    {
+        return $this->conn->write($query, $params);
+    }
+}
diff --git a/lib/databaseCommand/DatabaseConfig.php b/lib/databaseCommand/DatabaseConfig.php
new file mode 100644
index 0000000000000000000000000000000000000000..28014d05feed30d66d66b54d1d2524232c5057ec
--- /dev/null
+++ b/lib/databaseCommand/DatabaseConfig.php
@@ -0,0 +1,57 @@
+<?php
+
+namespace SimpleSAML\Module\perun\databaseCommand;
+
+use SimpleSAML\Configuration;
+
+class DatabaseConfig
+{
+    private const CONFIG_FILE_NAME = 'module_perun.php';
+    private const DATABASE = 'database';
+    private const STORE = 'store';
+
+    private const WHITELIST_TABLE_NAME = 'whiteListTableName';
+    private const GREYLIST_TABLE_NAME = 'greyListTableName';
+
+    private $config;
+    private $store;
+
+    private $whitelistTableName;
+    private $greyListTableName;
+
+    private static $instance = null;
+
+    private function __construct()
+    {
+        $configuration = Configuration::getConfig(self::CONFIG_FILE_NAME);
+
+        $this->config = $configuration->getConfigItem(self::DATABASE, null);
+        $this->store = $this->config->getConfigItem(self::STORE, null);
+
+        $this->whitelistTableName = $this->config->getString(self::WHITELIST_TABLE_NAME, null);
+        $this->greyListTableName = $this->config->getString(self::GREYLIST_TABLE_NAME, null);
+    }
+
+    public static function getInstance()
+    {
+        if (self::$instance === null) {
+            self::$instance = new self();
+        }
+        return self::$instance;
+    }
+
+    public function getStore()
+    {
+        return $this->store;
+    }
+
+    public function getWhitelistTableName()
+    {
+        return $this->whitelistTableName;
+    }
+
+    public function getGreyListTableName()
+    {
+        return $this->greyListTableName;
+    }
+}
diff --git a/lib/databaseCommand/IdpListsServiceDbCmd.php b/lib/databaseCommand/IdpListsServiceDbCmd.php
new file mode 100644
index 0000000000000000000000000000000000000000..808145e32892854f610f087556bce29a828bfbb0
--- /dev/null
+++ b/lib/databaseCommand/IdpListsServiceDbCmd.php
@@ -0,0 +1,130 @@
+<?php
+
+namespace SimpleSAML\Module\perun\databaseCommand;
+
+use PDO;
+use SimpleSAML\Logger;
+
+/**
+ * @author Dominik Baranek <baranek@ics.muni.cz>
+ * @author Pavel Vyskocil <vyskocilpavel@muni.cz>
+ */
+class IdpListsServiceDbCmd extends DatabaseCommand
+{
+    const WHITELIST = 'whiteList';
+    const GREYLIST = 'greyList';
+    const ENTITY_ID_COLUMN = 'entityId';
+    const REASON_COLUMN = 'reason';
+    const LOG_PREFIX = 'perun:IdpListsServiceDbCmd: ';
+
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    /**
+     * Function returns array of all IdPs in whitelist/greylist
+     * @param string $tableName 'whitelist' or 'greylist'
+     * @return array of all IdPs, every IdP is represents as array
+     */
+    public function getAllIdps($tableName)
+    {
+        $whiteListTableName = $this->config->getWhitelistTableName();
+        $greyListTableName = $this->config->getGreyListTableName();
+        $table = null;
+
+        if ($tableName === self::WHITELIST) {
+            $table = $whiteListTableName;
+        } elseif ($tableName === self::GREYLIST) {
+            $table = $greyListTableName;
+        }
+
+        $query = 'SELECT * FROM ' . $table;
+        $params = [];
+
+        return $this->read($query, $params)->fetchAll(PDO::FETCH_ASSOC);
+    }
+
+    /**
+     * Function returns array of all entityId in whitelist/greylist
+     * @param string $tableName 'whitelist' or 'greylist'
+     * @return array of entityIds
+     */
+    public function getAllEntityIds($tableName)
+    {
+        $whiteListTableName = $this->config->getWhitelistTableName();
+        $greyListTableName = $this->config->getGreyListTableName();
+        $table = null;
+
+        if ($tableName === self::WHITELIST) {
+            $table = $whiteListTableName;
+        } elseif ($tableName === self::GREYLIST) {
+            $table = $greyListTableName;
+        }
+
+        $query = 'SELECT ' . self::ENTITY_ID_COLUMN . ' FROM ' . $table;
+        $params = [];
+
+        return $this->read($query, $params)->fetchAll(PDO::FETCH_COLUMN);
+    }
+
+    /**
+     * Function inserts the line into table with $tableName
+     * @param string $tableName 'whitelist' or 'greylist'
+     * @param string $entityId
+     * @param string $reason
+     */
+    public function insertToList($tableName, $entityId, $reason)
+    {
+        $whiteListTableName = $this->config->getWhitelistTableName();
+        $greyListTableName = $this->config->getGreyListTableName();
+        $table = null;
+
+        if ($tableName === self::WHITELIST) {
+            $table = $whiteListTableName;
+        } elseif ($tableName === self::GREYLIST) {
+            $table = $greyListTableName;
+        }
+
+        $query = 'INSERT INTO ' . $table .
+            ' (' . self::ENTITY_ID_COLUMN . ', ' . self::REASON_COLUMN . ') VALUES' .
+            ' (:' . self::ENTITY_ID_COLUMN . ', :' . self::REASON_COLUMN . ')';
+
+        $params = [
+            self::ENTITY_ID_COLUMN => $entityId,
+            self::REASON_COLUMN => $reason
+        ];
+
+        if (!$this->write($query, $params)) {
+            Logger::error(self::LOG_PREFIX . 'Error while inserting into the database.');
+        }
+    }
+
+    /**
+     * Function deletes the line from table with $tableName and $entityID
+     * @param string $tableName 'whitelist' or 'greylist'
+     * @param string $entityId
+     */
+    public function deleteFromList($tableName, $entityId)
+    {
+        $whiteListTableName = $this->config->getWhitelistTableName();
+        $greyListTableName = $this->config->getGreyListTableName();
+        $table = null;
+
+        if ($tableName === self::WHITELIST) {
+            $table = $whiteListTableName;
+        } elseif ($tableName === self::GREYLIST) {
+            $table = $greyListTableName;
+        }
+
+        $query = 'DELETE FROM ' . $table . ' WHERE ' . self::ENTITY_ID_COLUMN . ' = :' . self::ENTITY_ID_COLUMN;
+
+        $params = [
+            self::ENTITY_ID_COLUMN => $entityId
+        ];
+
+        if (!$this->write($query, $params)) {
+            Logger::error(self::LOG_PREFIX . 'Error while deleting from the database.');
+        }
+    }
+}
diff --git a/www/getChallenge.php b/www/getChallenge.php
index 881c290d2244db1b5a1b396f1ca59d3497317aff..1a34950526538e124aec08a93ec561b51b0c9f9e 100644
--- a/www/getChallenge.php
+++ b/www/getChallenge.php
@@ -1,8 +1,7 @@
 <?php
 
-use SimpleSAML\Module\perun\DatabaseConnector;
 use SimpleSAML\Logger;
-use SimpleSAML\Module\perun\ScriptsUtils;
+use SimpleSAML\Module\perun\ChallengeManager;
 
 $entityBody = file_get_contents('php://input');
 $body = json_decode($entityBody, true);
@@ -39,10 +38,8 @@ try {
     exit;
 }
 
-$databaseConnector = new DatabaseConnector();
-$conn = $databaseConnector->getConnection();
-$generateChallengeSucceeded = ScriptsUtils::generateChallenge($conn, $challenge, $id, $scriptName);
-$conn->close();
+$challengeManager = new ChallengeManager();
+$generateChallengeSucceeded = $challengeManager->insertChallenge($challenge, $id, $scriptName);
 
 if (!$generateChallengeSucceeded) {
     exit;
diff --git a/www/updateUes.php b/www/updateUes.php
index 6ba041f198357fb7cc182461014e32d28f2522bd..d4dc24afa4b4724079e0e2285aa738a1faf0501c 100644
--- a/www/updateUes.php
+++ b/www/updateUes.php
@@ -21,8 +21,7 @@ use Jose\Component\Signature\Serializer\JWSSerializerManager;
 use SimpleSAML\Configuration;
 use SimpleSAML\Logger;
 use SimpleSAML\Module\perun\Adapter;
-use SimpleSAML\Module\perun\DatabaseConnector;
-use SimpleSAML\Module\perun\ScriptsUtils;
+use SimpleSAML\Module\perun\ChallengeManager;
 
 $adapter = Adapter::getInstance(Adapter::RPC);
 $token = file_get_contents('php://input');
@@ -82,15 +81,11 @@ try {
     $perunUserId = $claims['data']['perunUserId'];
     $id = $claims['id'];
 
-    $databaseConnector = new DatabaseConnector();
+    $challengeManager = new ChallengeManager();
 
-    $conn = $databaseConnector->getConnection();
-
-    $challengeDb = ScriptsUtils::readChallengeFromDb($conn, $id);
-    $checkAccessSucceeded = ScriptsUtils::checkAccess($conn, $challenge, $challengeDb);
-    $challengeSuccessfullyDeleted = ScriptsUtils::deleteChallengeFromDb($conn, $id);
-
-    $conn->close();
+    $challengeDb = $challengeManager->readChallengeFromDb($id);
+    $checkAccessSucceeded = $challengeManager->checkAccess($challenge, $challengeDb);
+    $challengeSuccessfullyDeleted = $challengeManager->deleteChallengeFromDb($id);
 
     if (!$checkAccessSucceeded || !$challengeSuccessfullyDeleted) {
         exit;