【发布时间】:2022-08-20 03:46:16
【问题描述】:
使用 razor pages 应用程序和 .NET 6,如何查找加密/解密数据?我做了一些研究,显然不推荐使用 AES-CBC 加密,这是我找到的替代方案(AES_256_GCM)。另外,有没有一种干净的方法可以将它变成一个可以在其他版本的 .NET 中重用的库(大型环境,升级所有东西都需要时间)?
它与其他关于在 .NET 核心中使用它的帖子很接近,但有一些小的(但“没有它就行不通”)调整:
程序.cs 文件:
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDataProtection();
builder.Services.AddDataProtection()
.UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration()
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_GCM,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
});
builder.Services.AddSingleton<CipherService>();
var app = builder.Build();
密码类:
using Microsoft.AspNetCore.DataProtection;
namespace Encryption.BusinessLogic
{
public class CipherService
{
private readonly IDataProtectionProvider _dataProtectionProvider;
private const string Key = \"my-very-long-key-of-no-exact-size\";
public CipherService(IDataProtectionProvider dataProtectionProvider)
{
_dataProtectionProvider = dataProtectionProvider;
}
public string Encrypt(string input)
{
var protector = _dataProtectionProvider.CreateProtector(Key);
return protector.Protect(input);
}
public string Decrypt(string cipherText)
{
var protector = _dataProtectionProvider.CreateProtector(Key);
return protector.Unprotect(cipherText);
}
}
}
索引页后面的代码:
private readonly ILogger<IndexModel> _logger;
private readonly IDataProtectionProvider _dataProtectionProvider;
[BindProperty]
public string InputText { get; set; }
[BindProperty]
public string Enc { get; set; }
public IndexModel(ILogger<IndexModel> logger, IDataProtectionProvider dataProtectionProvider)
{
_logger = logger;
_dataProtectionProvider = dataProtectionProvider;
}
public void OnGet()
{
}
public void OnPost()
{
CipherService cipher = new CipherService(_dataProtectionProvider);
Enc = cipher.Encrypt(InputText);
}
标签: c# encryption razor-pages .net-6.0