I m encrypting some sensitive data in my SQL db (i.e. SSN). I have have my encryption key saved in a table and with each encryption/Decryption request they key get called from the table.
public static class DbEncryptionHandler { public static string StaticDecrypt(string cipherText, ApplicationDbContext _context) { try { if (!string.IsNullOrWhiteSpace(cipherText)) { List<EncKeys> Keys = new List<EncKeys>(); Keys = _context.EncKeys.FromSql("EncKeysSP").ToList(); string EncryptionKey = Keys[0].StaticKey; cipherText = cipherText.Replace(" ", "+"); byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } } else { cipherText = null; } } catch (Exception ex) { throw; } return cipherText; } }
this is the controller
public async Task<IActionResult> Edit(long? id) { if (id == null) { return NotFound(); } var patReg = await _context.PatReg.SingleOrDefaultAsync(m => m.FileId == id); patReg.SNN = DbEncryptionHandler.StaticDecrypt(patReg.SNN, _context); if (patReg == null) { return NotFound(); } return View(patReg); } // POST: PatReg/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(long id, [Bind("FileId,FName,MName,LName,Dob,GenrId,StasId,NatyId,MarsId,CouyId,StaeId,CityId,OccnId,Email,SNN,PassNo,MobNo,LLine,MAdds,StrtNo,SDirn,AptNo,Locy,ALevl,PCode,Couy,ProeId")] PatReg patReg) { if (id != patReg.FileId) { return NotFound(); } if (ModelState.IsValid) { try { patReg.SNN = DbEncryptionHandler.StaticEncrypt(patReg.SNN, _context); _context.Update(patReg); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PatRegExists(patReg.FileId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(patReg); }
I m getting this error while saving
SqlException: New transaction is not allowed because there are other threads running in the session. System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction) await _context.SaveChangesAsync();
what am i doing wrong here?