How to gain access to Asp.Net Core encryption keys?

自闭症网瘾萝莉.ら 提交于 2019-12-01 06:58:43

问题


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



来源:https://stackoverflow.com/questions/42913017/how-to-gain-access-to-asp-net-core-encryption-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!