在 c# MVC 中跨控制器使用数据保护加密解密

use*_*535 4 c# encryption asp.net-core-mvc asp.net-core

我正在使用 IDataProtector 来保护和取消保护控制器内没有问题。我可以注射保护剂并使用它。

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);
    }
Run Code Online (Sandbox Code Playgroud)

这然后显示了加密和解密的“1”

然后我可以创建一个链接并将其传递给同一控制器上的另一个操作

<a asp-controller="Home"
   asp-action="GetKey"
   asp-route-id="@Model.encryptedtext">
    Pass Key to getkey
</a>
Run Code Online (Sandbox Code Playgroud)

这会传递加密数据并允许我在 GetKey 操作中解密。

public IActionResult GetKey(String id)
    {
        Test test = new Test();         
        test.encryptedtext = id;

        test.originaltext = _protector.Unprotect(id);
        return View(test);
    }
Run Code Online (Sandbox Code Playgroud)

如果我然后尝试创建一个链接并将其传递给另一个控制器。

 <a asp-controller="Key"
   asp-action="GetKeyController"
   asp-route-id="@Model.encryptedtext">
    Pass Key to other controller
</a>
Run Code Online (Sandbox Code Playgroud)

它因错误而失败

System.Security.Cryptography.CryptographicException: The payload was invalid
Run Code Online (Sandbox Code Playgroud)

关于我应该在哪里看的任何线索?

Dar*_*l42 5

在您的实例创建调用...

provider.CreateProtector(GetType().FullName)
Run Code Online (Sandbox Code Playgroud)

您提供当前类型的全名作为保护器的目的字符串...

您需要使用相同用途的字符串创建保护器和去保护器才能协同工作