小编use*_*535的帖子

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

我正在使用 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: …
Run Code Online (Sandbox Code Playgroud)

c# encryption asp.net-core-mvc asp.net-core

4
推荐指数
1
解决办法
2079
查看次数

标签 统计

asp.net-core ×1

asp.net-core-mvc ×1

c# ×1

encryption ×1