Click here to Skip to main content
15,885,216 members
Articles / Web Development / ASP.NET

Data Security in ASP.NET Core

Rate me:
Please Sign up or sign in to vote.
4.10/5 (9 votes)
21 Nov 2016CPOL8 min read 27.3K   9  
This article give you idea about How data security is handled in ASP.NET Core using Data protection API

What is ASP.NET Core

ASP.NET designed and introduced 15 years ago, since then millions of developers has used it and built great web applications, Almost each year Microsoft come up with new features and add different capabilities to make it more stronger. Now to fit todays modern technology requirement they have introduced ASP.NET Core, which is open-source and cross-platform framework (run on Windows, Mac, Linux, including RedHat and Ubuntu) which helps you to latter-day apps like cloud apps, IoT's, Mobile apps etc. ASP.NET Core is released by Microsoft in June 2016 [See here]

Why we need ASP.NETCore

Now the main concern is, why we need ASP.NET Core ? or why to use it ? What are its advantage over ASP.NET ? Now a days Web applications are not just limited to Desktops and laptops, it moved to smart devices, cloud apps, mobiles and IoT's, additionally it moved to other platforms too (Linux, Mac). To serve all these (basic) needs we need ASP.NET Core.

Basically ASP.NET Core is no longer depend upon system.web.dll It has inbuilt set of NuGet packages in it, which allows to optimize the App size, performance, security and rapid development, so inshort we moved to 'pay-for- what-you-use' theme.

Here are some of its key features

  • Open Source : It is open-source (linked with MIT and Apache 2 licenses)
  • Compatibility : It is widely compatible with .NET framework, Mono and Xamrin
  • Ease in Deployment
  • Light-weight and modular
  • Cross plat-form support
  • Host on IIS or Self host capability

.NET Framework vs .NET Core

Surely .NET is a stable and consistent framework, serving millions of web applications over a decade. It is ready to use framework with millions of preloaded libraries, Still there are some flaws in it e.g. it only supports Windows, its large API collection leads slow down performance etc.

Whereas .NET Core is it lighter than .NET framework, as it does not carry any API package, Just user need to install packages from NuGet and create customized app. It has a set of libraries called 'CoreFX' with a runtime called as 'CoreCLR', both libraries and runtime distributed through NuGet so user has to download it as per their requirement.

Running code on .NETCore is really easy, Just you need to Install .NET Core SDK --> Initialize some code --> Run the app --> you are done.

(Here, i am not giving first program in ASP.NET Core, as this article meant to cover Security aspect in ASP.NET Core, so please Excuse me)

Security in Web application

Over the years and years people struggling to secure web application and its data. Unlike windows desktop application, web application does not have Data Protection API (DPAPI) to protect and encrypt data, but ASP.NET Core has a very nice way to secure your data. It has protection stack with a API that will help us to to encrypt data with key management. Basically these cryptographic API has been re-designed to over come all problems that exists in current framework

Data security requirements

Data Security Expectation is simple, my data should be secure between server round trips, even if there is a un-trusted client call. so after server round trip server should have assurance that data is untouched. in short we need a Authentic data transfer.

Due to modularization and customizations development technique, components are re-used anywhere regardless of the system, here we need to ensure that data not should get messed-up with each other. The things we used to encrypt data such as filepath, access permission, server side storage should be confident and should not disclosed to untrusted client.

In simple words, the data security design should be Authentic, Secure, Simple to implement, Isolate from regular operations, Core logic should be hidden from developer.

Security Strategies

Keeping all above requirement in mind, ASP.NET Core has come up with below security strategies

  1. Develop a data security system which needs less configuration
  2. Key Logic should not be disclosed to developer, more even developer does not have access to raw cypher text
  3. Encrypted Key should be maintained and protected by system itself

To grab all requirements ASP.NET Core come up with data protection stack, API that helps us to implement encryption and hashing mechanisms .

What is Data protection API and Who can use it

Basically Data protection API create and manage a secrete key for encryption, it can used by 3 types of users

- Application and framework developers, who don't want to know how Data protection API and stack working and how it is configured, just wants to pass the input and get output from API

- System Admin and Developers, who don't want to store their secret file and keys on default path with default settings. So that nobody can easily track it. e.g. program default TEMP data should not store to '%AppData%' path (which is default path), ASP.NET Core has 'IDataProtectionBuilder' interface which allow us to change all default path and settings

For data protection, ASP.NET core support both encryption and hashing technique. Now the question comes in mind, what is encryption and hashing ? If both are used for security then what is difference between encryption and hashing ?

Encryption vs Hashing

Encryption is the process of turning data in to series of unreadable and unsequential characters that are not fixed in length, it needs a key to encrypt data, Encrypted string is known as ciphertext, so with the help of scret key and encryption algorithm we can generate ciphertext. Some popular encryption algorithm are DES, Triple DES, AES etc

Hashing is the process if turning data in a fixed length of string or numbers, here, same input always generates same output.  Once is the data is hashed it cannot be fetch back to original text. so we will never actual data that we have passed. Some popular hashing technique are MD5, SHA etc.

The big difference between Encryption and Hashing is, we can create encrypted to plain text in encryption but we cannot to back to original text from hashed text.

Namespaces and Classes

'Microsoft.AspNetCore.DataProtection' is the core namespace, if you just want to use the Data protection API and don't want to learn its machanism just refer 'Microsoft.AspNetCore.DataProtection.Abstractions' namesapce. 'Microsoft.AspNetCore.DataProtection.Extensions ' is used to take advantages of additional APIs that which is not belong to core packages.  'Microsoft.AspNetCore.Cryptography.KeyDerivation' used for password hashing

Using API

Use of Data protection is really simple, just you need to import 'AspNetCore.DataProtection' and 'Extensions.DependencyInjection' namesapces, and to protect your data you need to use protect() method (To use protect() method we need to create data protector using data protection provider) that's it. we have done. Lets see how it works

Encryption using ASP.NET Core

Encryption needs a Key to encrypt data, but here, key is created and maintained by API itself, these keys are generated with the default lifespan of 90 days and stored at a secrete (maybe we call it as suitable) location. This Key is temporary, the data protection API is designed to secure short term data like Querystring, cookies etc.

see below snippet

C#
using System;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;

public class Program
{
    public static void Main(string[] args)
    {
        //use data protection services
        var SCollection = new ServiceCollection();

       //add protection services
        SCollection.AddDataProtection();
        var SerPro = SCollection.BuildServiceProvider();

        // create an instance of classfile using 'CreateInstance' method
        var instance = ActivatorUtilities.CreateInstance<ProClass>(SerPro);
        instance.getPutOut();
    }

    public class ProClass
    {
        IDataProtector _iPro;

        // the 'provider' parameter is provided by DI
        public ProClass(IDataProtectionProvider provider)
        {
            _iPro = provider.CreateProtector("ProClass");
        }

        public void getPutOut()
        {
            string input = "Hello World";

            // protect string
            string protectedString = _iPro.Protect(input);
           
            // protect string
            string unProtectedString = _iPro.Unprotect(protectedString);
        }
    }
}

//output
input : "Hello World"
protectedString : CfDJ8ICcgQwZZhlAlTZT....
unprotectedeString : "Hello World"

In above sample we have create a 'ServiceCollection' object which is used to create and add data protection services, then we create a instance of our class using 'CreateInstance' method, This method is exposed by 'ActivatorUtilities' class (which is a static helper class from 'Microsoft.Framework.DependencyInjection' namesapce, it has some inbuilt methods that are help to deal with constructor parameters) , finally we simply call 'Protect' and 'Unprotect' method

** Have you notice one thing here? We have pass a string to 'CreateProtector' method, Do you know what that string indicate?  it is call 'purpose string' basically it is used to create a isolated environment, e.g. if we create a protector with a string 'ABC' and protect a data, it cannot be unprotect same data with a protector created with string 'XYZ', so it is again a step forward to make data more secure.

Hashing using ASP.NET Core

With the help of 'Microsoft.AspNetCore.Cryptography.KeyDerivation' package we can implement hashing using ASP.NET Core, it has 'Pbkdf2'method which uses 'PBKDF2 algorithm' to hashed a data. see below snippet to know how to secure data using hashing

C#
using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
 
public class Program
{
    public static void Main(string[] args)
    {
        string SimpleText = "myText";
 
        //Generate a 128-bit salt
       //**Salt: it is nothing but a random number
        byte[] Slt = new byte[128 / 8];
        using (var RandomNum = RandomNumberGenerator.Create())
        {
            RandomNum.GetBytes(Slt);
        }
 
        // Create 256-bit key using HMACSHA1 algorithm with 1000 iterations
        string secureHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
            password: SimpleText,
            salt: Slt,
            prf: KeyDerivationPrf.HMACSHA1,
            iterationCount: 1000,
            numBytesRequested: 256 / 8));

        System.IO.AppendAllText("D:\\hashed.txt", "HashedText : " + secureHash);
    }
}

In above sample with the help of a salt and 'HMACSHA1' algorithm (1000 iterations) we have hashed a string to encrypted text.

So what's wrong with current .NET framework Hash algorithm

Here the point is, why i need ASP.NET Core to make hashed string, what's wrong with current .NET framework Hash algorithm ? Current .NET Framework has 'Rfc2898DeriveBytes' Class which used to create a hashed string but there are some limitations

  •  It only supports HMACSHA1 algorithm, where as 'KeyDerivation.Pbkdf2' supports HMACSHA1, HMACSHA256, HMACSHA512
  • 'KeyDerivation.Pbkdf2' supports Performance improvement depend upon operating system, (basically it auto detects operating system and implement most optimized way)
  • We can specify input parameters for hashing (e.g. Salt value, algorithm, iteration count), current .NET hashing class has provided inbuilt default values for this.

 

Where to use this API

ASP.NET Core Encryption technique can be good to use at client state management technique like Querystring and Cookies, due to auto generation encryption key, it plays a secure role.

ASP.NET Core Hashing technique is good to use for storing password (as it cannot go back to original text)

References

https://docs.microsoft.com/en-us/aspnet/core/

https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/introduction

Finally

ASP.NET Core provides a protection API that helps us to encrypt data using Encryption and Hashing technique, additionally for encryption, key is created and maintain by system itself so outside interference get blocked and data get more secured.

Data security is not a single cup of tea, there are lot to discuss and share, we will cover it in articles till then Enjoy this Encryption and Hashing points and get secured.

- Happy Security

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Hi there, I am Prasad. Author, Blogger, contributor and passionate about Microsoft .NET technologies. I like to write an articles/blogs on different .NET aspects and like to help Developers, to resolve their issues and boost them on Microsoft Technologies.


Certifications: Microsoft Certified professional (MCP), Microsoft Certified technology specialist (MCTS), Agile-Scrum Master.


Awards: Microsoft Re-connect MVP (GSC Member), Most valuable member at dotnetspider, Most popular curator, Most active curator, featured curator at Microsoft Curah, Editor at dotnetspider.


Microsoft MVP 2014 [ASP.NET/IIS]
Click here for more .NET Tips
-After all Knowledge is an endless entity

Comments and Discussions

 
-- There are no messages in this forum --