在.NET Core 3.1中,可以使用Data Protection API(DPAPI)来加密和解密敏感数据。下面是使用DPAPI加密和解密数据的示例代码:
加密数据:
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace DataProtectionExample
{
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddDataProtection();
var serviceProvider = services.BuildServiceProvider();
var protector = serviceProvider.GetDataProtector("MyApp.DataProtectionExample");
string plainText = "This is a secret message";
string encryptedText = protector.Protect(plainText);
Console.WriteLine($"Encrypted Text: {encryptedText}");
}
}
}
解密数据:
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace DataProtectionExample
{
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddDataProtection();
var serviceProvider = services.BuildServiceProvider();
var protector = serviceProvider.GetDataProtector("MyApp.DataProtectionExample");
string encryptedText = "Encrypted text here";
string decryptedText = protector.Unprotect(encryptedText);
Console.WriteLine($"Decrypted Text: {decryptedText}");
}
}
}
在上面的示例中,我们使用AddDataProtection
方法将Data Protection API添加到服务集合中。然后,我们通过调用GetDataProtector
方法获取一个特定的数据保护程序,该保护程序使用给定的应用程序名称进行配置。最后,我们可以使用Protect
方法加密数据,并使用Unprotect
方法解密数据。
请注意,为了在ASP.NET Core中使用Data Protection API,您需要引用Microsoft.AspNetCore.DataProtection
和Microsoft.AspNetCore.DataProtection.Extensions
包。