I would like to encrypt a string in .NET Core using a key. I have a client / server scenario and would like to encrypt a string on the client, send it to the server and decr
The data protection system is enabled by default for ASP.NET Core applications. You don't even need to do anything in your StartUp method unless you want to reconfigure the default key storage location or the life time of keys. In which case you'd do the following in your ConfigureServices method:
services.ConfigureDataProtection(dp =>
{
dp.PersistKeysToFileSystem(new DirectoryInfo(@"c:\keys"));
dp.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
});
Because the data protection system is in the application's services collection by default, it can be made available via dependency injection. Here's how you can inject the IDataProtectionProvider into a controller and then use it to create an instance of an IDataProtector in the controller's constructor:
public class HomeController : Controller
{
IDataProtector _protector;
public HomeController(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector(GetType().FullName);
}
}
You can then call the protector to encrypt content like this:
public IActionResult Index()
{
var model = _service.GetAll().Select(c => new ContractViewModel {
Id = _protector.Protect(c.Id.ToString()),
Name = c.Name }).ToList();
return View(model);
}
I hope this helps :)