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

时间:2017-09-04 10:45:03

标签: c# encryption asp.net-core asp.net-core-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);
    }

然后显示加密和解密的" 1"

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

<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);
    }

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

 <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

有关我应该看的地方的任何线索?

2 个答案:

答案 0 :(得分:2)

在实例创建调用中

...

provider.CreateProtector(GetType().FullName)

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

你需要使用相同的目的字符串创建保护器和deprotector才能一起工作

答案 1 :(得分:0)

好的,发帖后不久我发现我做错了什么。我没有意识到,当你创建你的保护器时,你应该使用钥匙......

 _protector = provider.CreateProtector("KeyHere");