/// <summary> /// Upgrades to 00.09.00 /// /// Operations: /// - Generate a Salt. /// - Hash existing APIKeys using the new Salt. /// - Encrypt existing EncryptionKeys using plain text APIKey. /// - Insert in to new table. /// </summary> private void Upgrade_00_09_00() { string oldTableName = "{databaseOwner}[{objectQualifier}Cantarus_PolyDeploy_APIUsers_PreEncryption]"; string newTableName = "{databaseOwner}[{objectQualifier}Cantarus_PolyDeploy_APIUsers]"; using (IDataContext context = DataContext.Instance()) { // Get all existing api user ids. IEnumerable <int> apiUserIds = context.ExecuteQuery <int>(System.Data.CommandType.Text, $"SELECT [APIUserID] FROM {oldTableName}"); foreach (int apiUserId in apiUserIds) { // Read old data. string auName = context.ExecuteQuery <string>(System.Data.CommandType.Text, $"SELECT [Name] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); string auApiKey = context.ExecuteQuery <string>(System.Data.CommandType.Text, $"SELECT [APIKey] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); string auEncryptionKey = context.ExecuteQuery <string>(System.Data.CommandType.Text, $"SELECT [EncryptionKey] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); bool auBypass = context.ExecuteQuery <bool>(System.Data.CommandType.Text, $"SELECT [BypassIPWhitelist] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); // Generate a salt. string auSalt = APIUser.GenerateSalt(); // Use existing plain text api key and salt to create a hashed api key. string auApiKeySha = APIUser.GenerateHash(auApiKey, auSalt); // Encrypt existing plain text encryption key and store in new field. string auEncryptionKeyEnc = Crypto.Encrypt(auEncryptionKey, auApiKey); // Insert in to new table. string insertSql = $"SET IDENTITY_INSERT {newTableName} ON;" + $"INSERT INTO {newTableName} ([APIUserID], [Name], [APIKey_Sha], [EncryptionKey_Enc], [Salt], [BypassIPWhitelist])" + $"VALUES (@0, @1, @2, @3, @4, @5);" + $"SET IDENTITY_INSERT {newTableName} OFF;"; context.Execute(System.Data.CommandType.Text, insertSql, apiUserId, auName, auApiKeySha, auEncryptionKeyEnc, auSalt, auBypass); } } }