How to gain access to Asp.Net Core encryption keys

2019-02-26 04:31发布

问题:

A cookie provided by call:

await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal);

is stored in encrypted state. How to get encryption key?

IMPORTANT: this question has grown from my original question about cookie decryption. Thanks to Ron C and his great answer.

回答1:

Gaining Access to the Keys
By default the .net core framework goes to great lengths to keep the keys private and to help the developer to avoid any need for handling the keys. This is good as it's quite difficult for developers to keep keys safe.

That said, with a change of configuration you can easily gain access to the keys.

Add the following line of code to the ConfigureServices method of the Startup.cs file. If you use use session, add it below the line for AddSession:

 services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(keyDirPath));

and set keyDirPath to the operating system absolute path of the directory that you'd like the keys stored in. The directory does not need to already exist as the system will create it on the fly. In my case I set directory to a folder named Keys. Here's what the directory looked like after running the code once, it contains one key file:

The contents of that key file are unencrypted and look like this:

<?xml version="1.0" encoding="utf-8"?>
  <key id="677f1115-644a-4b11-b045-0c3c51675ef1" version="1">
    <creationDate>2017-03-17T12:21:10.8909291Z</creationDate>
    <activationDate>2017-03-17T12:21:10.8419262Z</activationDate>
    <expirationDate>2017-06-15T12:21:10.8419262Z</expirationDate>
    <descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=1.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60">
      <descriptor>
        <encryption algorithm="AES_256_CBC" />
        <validation algorithm="HMACSHA256" />
        <masterKey p4:requiresEncryption="true" xmlns:p4="http://schemas.asp.net/2015/03/dataProtection">
          <!-- Warning: the key below is in an unencrypted form. -->
          <value>BMJ6EY5MbcR0vaXhCbHggQcVsuYc6MnMtQpQm0qL647UBVx0YDbZufqQ+2/XuahFfIY2fJ6BIlOl+LYODnLbrA==</value>
        </masterKey>
      </descriptor>
    </descriptor>
  </key>

WARNING: You should never leave your keys laying around in a totally unprotected state in a folder named keys. Doing so is not a security best practice. But if you are trying to learn about the security system, it's a useful exercise.

You can learn more about the Data protection services here: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview