Today, Web and data security has become a major concern to most of the enterprises. It is important for Web developers to build websites to secure sensitive data and not expose it to the outside world or unauthorized people. I’m sure as a developer, you may come across URLs where some parameters are passed in the URL to indentify users and other parameters values.
For example,

Now, the question is can we encrypt this id to some non-readable format for the outer world and use it decrypted format for internal within calling code which is finally compiled to some DLL or EXE.
For example,
This will surely help us to prevent sensitive data from being misused, let's jump to code snippets in order to understand the development approach, here we will use the inbuilt feature of .NET core DataProtectorTokenProvider. It will take care of encrypting and decrypting our private data (Query Parameter) or any other sensitive data.
In .NET Core, each service, middleware, class, and interface handled through dependency injection. this is why DI is used properly using scoped, singleton, transient. let's create a custom class with CustomIDataProtector.cs define the encode and decode methods which will use internally use Protect() and Unprotect() methods of IDataProtector interface.
- namespace DemoDecodeURLParameters.Security {
- public class CustomIDataProtection {
- private readonly IDataProtector protector;
- public CustomIDataProtection(IDataProtectionProvider dataProtectionProvider, UniqueCode uniqueCode) {
- protector = dataProtectionProvider.CreateProtector(uniqueCode.BankIdRouteValue);
- }
- public string Decode(string data) {
- return protector.Protect(data);
- }
- public string Encode(string data) {
- return protector.Unprotect(data);
- }
- }
- }
Register this class in the .NET core DI container. We also added Uniquecode it's your secret key to make additional security we need the same key for protecting and unprotect your sensitive data.
- public class UniqueCode {
- public readonly string BankIdRouteValue = "BankIdRouteValue";
- }
- public void ConfigureServices(IServiceCollection services) {
- services.AddSingleton < UniqueCode > ();
- services.AddSingleton < CustomIDataProtection > ();
- }
Let's use CustomIDataProtection this in .Net core pages
- public class IndexModel: PageModel {
- private readonly CustomIDataProtection protector;
- public IndexModel(CustomIDataProtection customIDataProtection) {
- protector = customIDataProtection;
- }
- public void OnGet() {
- DomainModel dm = new DomainModel();
- dm.BankId = 2020202020;
- dm.DecodeId = protector.Decode(dm.BankId.ToString());
- ViewData["BankData"] = dm;
- }
- }

nitin patilPosted Aug 27, 2021, 1:34 PM
This in nice article. I think Encode and decode functions are written incorrectly.It should be, public string Decode(string data) { return protector.Unprotect(data); } public string Encode(string data) { return protector.Protect(data); }
Sourav Kumar DasPosted Oct 31, 2019, 12:02 AM
Nice Article.