c# - 在跨 Controller 的 c# MVC 中使用数据保护加密解密

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

我正在使用 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/

相关文章:

c# - 如何在另一个旁边显示动态创建的 DIV?

java - Android 中使用 RSA 解密 AES key

c# - .NET Core DI,将参数传递给构造函数的方法

owin - 如何在Startup.cs中添加CamelCasePropertyNamesContractResolver?

c# - DbSet 在 EF7 中没有 Find 方法

c# - 枚举中相等运算符和运算符之间的区别

c# - NHibernate 的 ISQLQuery 返回非预期类型的​​实例

go - 无法解密二进制文件

java - 使用 AES-CFB 在 Python 中加密并在 Java 中解密

c# - 启动 ConfigureServices AddMvc() 中的 KeyNotFoundException