• 6 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 12/20/19

Implement Data Protection With Consumer APIs

Protecting Data is Simple!

Protecting data, at its simplest level (and honestly, this is really what the DPS is primarily designed for), is accomplished with just three steps:

  1. Create a data protector from a data protection provider.

  2. Call the  Protect  method with the data you want to protect.

  3. Call the  Unprotect  method with the data you want to turn back into plain text.

That’s it.

The following is an example from Microsoft’s DPS documentation that demonstrates the simplicity of the DPS design. See if you can spot the three steps. For clarity, you can see the sample’s output at the end.

using System;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
 
public class Program
{
    public static void Main(string[] args)
    {
        // add data protection services
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddDataProtection();
        var services = serviceCollection.BuildServiceProvider();
 
        // create an instance of MyClass using the service provider
        var instance = ActivatorUtilities.CreateInstance<MyClass>(services);
        instance.RunSample();
    }
 
    public class MyClass
    {
        IDataProtector _protector;
 
        // the 'provider' parameter is provided by DI
        public MyClass(IDataProtectionProvider provider)
        {
            _protector = provider.CreateProtector("Contoso.MyClass.v1");
        }
 
        public void RunSample()
        {
            Console.Write("Enter input: ");
            string input = Console.ReadLine();
 
            // protect the payload
            string protectedPayload = _protector.Protect(input);
            Console.WriteLine($"Protect returned: {protectedPayload}");
 
            // unprotect the payload
            string unprotectedPayload = _protector.Unprotect(protectedPayload);
            Console.WriteLine($"Unprotect returned: {unprotectedPayload}");
        }
    }
}
 
/*
 * SAMPLE OUTPUT
 *
 * Enter input: Hello world!
 * Protect returned: CfDJ8ICcgQwZZhlAlTZT...OdfH66i1PnGmpCR5e441xQ
 * Unprotect returned: Hello world!
 */

Let’s Recap!

In this chapter, you saw how simple it is to implement the data protection capability of the .NET Core data protection system. You learned that the three primary steps for protecting data consist of:

  1. Creating a data protector from a provider.

  2. Calling the  Protect  method with the data you want to protect.

  3. Calling the  Unprotect  method to restore the data. 

In the next chapter, you’ll learn about SSL and HTTPS and how to use them to further secure your applications.

Example of certificate of achievement
Example of certificate of achievement