我正在使用 IDataProtector 在 Controller 内毫无问题地保护和取消保护。我可以注入(inject)保护剂并使用它。
IDataProtector _protector;
public HomeController(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector(GetType().FullName);
}
public IActionResult Index()
{
Test test = new Test();
test.originaltext = "1";
test.encryptedtext = _protector.Protect(test.originaltext);
test.originaltext = _protector.Unprotect(test.encryptedtext);
return View(test);
}
然后显示加密和解密的“1”
然后我可以创建一个链接并将其传递给同一 Controller 上的另一个操作
<a asp-controller="Home"
asp-action="GetKey"
asp-route-id="@Model.encryptedtext">
Pass Key to getkey
</a>
这会传递加密数据并允许我在 GetKey 操作中解密。
public IActionResult GetKey(String id)
{
Test test = new Test();
test.encryptedtext = id;
test.originaltext = _protector.Unprotect(id);
return View(test);
}
如果我然后尝试创建一个链接并将其传递给另一个 Controller 。
<a asp-controller="Key"
asp-action="GetKeyController"
asp-route-id="@Model.encryptedtext">
Pass Key to other controller
</a>
失败并出现错误
System.Security.Cryptography.CryptographicException: The payload was invalid
关于我应该看哪里的任何线索?
最佳答案
在你的实例创建调用中......
provider.CreateProtector(GetType().FullName)
您提供当前类型的全名作为保护器的目的字符串...
您需要使用相同目的字符串创建保护器和去保护器才能协同工作
关于c# - 在跨 Controller 的 c# MVC 中使用数据保护加密解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46035377/