using System;using Microsoft.AspNetCore.DataProtection;using Microsoft.Extensions.DependencyInjection;public class Program{public static void Main(string[] args){// 添加数据保护到服务中var serviceCollection = new ServiceCollection();serviceCollection.AddDataProtection();var services = serviceCollection.BuildServiceProvider();// 从DI中创建一个MyClass的实例 var instance = ActivatorUtilities.CreateInstance<MyClass>(services);instance.RunSample();}public class MyClass{IDataProtector _protector;// 参数 "provider" 来自 DIpublic MyClass(IDataProtectionProvider provider){_protector = provider.CreateProtector("Contoso.MyClass.v1");}public void RunSample(){Console.Write("Enter input: ");string input = Console.ReadLine();// 加密string protectedPayload = _protector.Protect(input);Console.WriteLine($"Protect returned: {protectedPayload}");// 解密string unprotectedPayload = _protector.Unprotect(protectedPayload);Console.WriteLine($"Unprotect returned: {unprotectedPayload}");}}}/* * 输出: * * Enter input: Hello world! * Protect returned: CfDJ8ICcgQwZZhlAlTZT...OdfH66i1PnGmpCR5e441xQ * Unprotect returned: Hello world! */在CreateProtector("Contoso.MyClass.v1")中,参数“Contoso.MyClass.v1”可以理解为一个公钥,因为 ASP.NET Core Data Protection 是非对称加密(见前面介绍),所以系统中应该还有一个密钥,那么此处的密钥 ASP.NET Core 在系统内部帮你维护了。
程序抛出了一个“System.Security.Cryptography.CryptographicException”异常的结果。
为什么呢? 这是因为每一台机器都有一个自有的私钥,由于在解密的过程中,这个私钥是不同的,所以解密失败,抛出了一个异常。
私钥
私钥存放在哪里呢?
1、如果程序寄宿在 Microsoft Azure下,存储在“%HOME%ASP.NETDataProtection-Keys” 文件夹。
2、如果程序寄宿在IIS下,它被保存在HKLM注册表的ACLed特殊注册表键,并且只有工作进程可以访问,它使用windows的DPAPI加密。
3、如果当前用户可用,即win10或者win7中,它存储在“%LOCALAPPDATA%ASP.NETDataProtection-Keys”文件夹,同样使用的windows的DPAPI加密。
4、如果这些都不符合,那么也就是私钥是没有被持久化的,也就是说当进程关闭的时候,生成的私钥就丢失了。
下面是博主机器上的私钥文件:
一个xml配置文件,位于C:Users用户名AppDataLocalASP.NETDataProtection-Keys文件夹,名为:key-c37e3ed9-fbb5-47bc-9e8c-128afaf1c6d9.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?><key id="c37e3ed9-fbb5-47bc-9e8c-128afaf1c6d9" version="1"> <creationDate>2016-08-15T05:21:16.7925949Z</creationDate> <activationDate>2016-08-15T05:21:16.7165905Z</activationDate> <expirationDate>2016-11-13T05:21:16.7165905Z</expirationDate> <descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"><descriptor> <encryption algorithm="AES_256_CBC" /> <validation algorithm="HMACSHA256" /> <encryptedSecret decryptorType="Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60" xmlns="http://schemas.asp.net/2015/03/dataProtection"><encryptedKey xmlns=""> <!-- This key is encrypted with Windows DPAPI. --> <value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAArS6GBZu5C024S8VcNDckGgAAAAACAAAAAAAQZgAAAAEAACAAAABBUO4j0CscEZsdcHDAStXnDvtx+zFucmsG90sdhyjfgQAAAAAOgAAAAAIAACAAAABGr9fgvZkLAlgIZkGym5uLiufpaEcuVsp35+J96ItTYlABAADEZxVArK0QtxufuaRt/kVR2ZBZEoLhlYJ44BhvQDd6b9tN0L9Y7W2eeBPBefcZaGZk5xILwZYI5box9omwC/mp8t9wopVaratjZuNs21Al+JzxS+PeV9X0iPtRyfx2K7DJYOUT6IqoFR2ykL5MI9jvkIbUxcQOs0BKOwAHl4yAlYF2tR8pz1FkXKqZafovc11aOZeZhkfd2hiA53tan94bQOP43Z4HF+QWSazrq5IIqdFSOyZQemWL9Z7eYyoNpEktf3eGZQu/KBOg/BH5yizWa+6b7RLcEX6JdQ2/jpmnHNl+HPMIah3UZV0mRfAE2j58cUjosnV+LDQZoLn4OP70YWtO/tTBc4tsEY3n/WboL4PgPPmQ+2jfd/zmEQIon+4d7TY+mGh4c6wXAmAZF517UAHQMC1icx4HSJC8DTuWPlINihPyufejuPmLqW6CW8NAAAAA7ziObXv+Ax4Mm0AtZiGw0/IepDv/gJSxhEwLIDhfvQIQJv//G500EYtIbZJW6sWit//ypfjrUZYglHgKV+GpbA==</value></encryptedKey> </encryptedSecret></descriptor> </descriptor></key>文件包含一个创建日期,一个过期日期。间隔为90天,当90天之后密钥就会失效,系统将自动生成一个新的密钥并设置新的密钥作为活动的密钥。只要已过期的密钥还存在于系统上,你仍然可以解密任何受保护的数据。