| 111 | } |
| 112 | |
| 113 | void SQLiteUtils::validateEncryption( |
| 114 | const std::string &sqliteFilePath, |
| 115 | const std::string &encryptionKey) { |
| 116 | std::string temp_encrypted_db_path = sqliteFilePath + "_temp_encrypted"; |
| 117 | |
| 118 | bool temp_encrypted_exists = SQLiteUtils::fileExists(temp_encrypted_db_path); |
| 119 | bool default_location_exists = SQLiteUtils::fileExists(sqliteFilePath); |
| 120 | |
| 121 | if (temp_encrypted_exists && default_location_exists) { |
| 122 | Logger::log( |
| 123 | "Previous encryption attempt failed. Repeating encryption process from " |
| 124 | "the beginning."); |
| 125 | SQLiteUtils::attemptDeleteFile( |
| 126 | temp_encrypted_db_path, |
| 127 | "Failed to delete corrupted encrypted database."); |
| 128 | } else if (temp_encrypted_exists && !default_location_exists) { |
| 129 | Logger::log( |
| 130 | "Moving temporary encrypted database to default location failed in " |
| 131 | "previous encryption attempt. Repeating rename step."); |
| 132 | SQLiteUtils::attemptRenameFile( |
| 133 | temp_encrypted_db_path, |
| 134 | sqliteFilePath, |
| 135 | "Failed to move encrypted database to default location."); |
| 136 | return; |
| 137 | } else if (!default_location_exists) { |
| 138 | Logger::log( |
| 139 | "Database not present yet. It will be created encrypted under default " |
| 140 | "path."); |
| 141 | return; |
| 142 | } |
| 143 | |
| 144 | if (SQLiteUtils::isDatabaseQueryable(true, sqliteFilePath, encryptionKey)) { |
| 145 | Logger::log( |
| 146 | "Database exists under default path and it is correctly encrypted."); |
| 147 | return; |
| 148 | } |
| 149 | |
| 150 | if (!SQLiteUtils::isDatabaseQueryable(false, sqliteFilePath, encryptionKey)) { |
| 151 | Logger::log( |
| 152 | "Database exists but it is encrypted with key that was lost. " |
| 153 | "Attempting database deletion. New encrypted one will be created."); |
| 154 | SQLiteUtils::attemptDeleteFile( |
| 155 | sqliteFilePath.c_str(), |
| 156 | "Failed to delete database encrypted with lost key."); |
| 157 | return; |
| 158 | } else { |
| 159 | Logger::log( |
| 160 | "Database exists but it is not encrypted. Attempting encryption " |
| 161 | "process."); |
| 162 | } |
| 163 | |
| 164 | sqlite3 *db; |
| 165 | sqlite3_open(sqliteFilePath.c_str(), &db); |
| 166 | |
| 167 | std::string createEncryptedCopySQL = "ATTACH DATABASE '" + |
| 168 | temp_encrypted_db_path + |
| 169 | "' AS encrypted_comm " |
| 170 | "KEY \"x'" + |