Search code examples
asp.net-core-webapiasp.net-core-2.2

Query encrypted data in .netcore 2


I have followed microsoft's official guide of encrypting and decrypting data. My problem is how can I search the data of database for a given property. For example I want to query all the data in database where FirstName contains the search name I entered. But FirstName is encrypted in the database so it has this value: "CfDJ8GJ0pjnzz6BGph-AUfSYepqLrRxw5zqtqoh540M8wHqnnfZRuH542PMzLClloeYoQAq69kPRmUHnNdfg7J9jHc9ieIe1Vx9I_IQgt-XjUt5QE9lHknB1IKIZW6IAz_zh_w"

I can protect and unprotect data successfully when data have been retrieved but I can't query data on the go. To decrypt data, I use _protector.Unprotect(), but when I put it in where(), it does nothing and I don't get any errors. The code above doesn't work for some reason.

var customers = await _context.Customers
            .Include(x => x.CustomerInformation)
            .Include(x => x.CustomerContact)
            .Where(x => _protector.Unprotect(x.CustomerInformation.FirstName).Contains(name))
            .ToListAsync();         

Solution

  • I fixed it! The problem was occuring when first name was created with capital letters. So my updated code for querying encypted data is this:

    var customers = await _context.Customers
        .Include(x => x.CustomerInformation)
        .Include(x => x.CustomerContact)
        Where(x => 
                (_protector.Unprotect(x.CustomerInformation.FirstName).ToLower().Contains(name)) ||
                (_protector.Unprotect(x.CustomerInformation.LastName).ToLower().Contains(name)) ||
                (x.CustomerInformation.Code.ToLower().Contains(name))
             )
             .ToListAsync();