2017-09-04 25 views
1

我是否正在使用IDataProtector在控制器內保護和解除保護而沒有問題。我可以注入保護器並使用它。在控制器中使用c#MVC中的數據保護加密解密

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 

任何線索?

在您實例創建呼叫

回答

1

...

provider.CreateProtector(GetType().FullName) 

您提供當前類型的全名作爲宗旨字符串保護...

,你將需要保護和deprotector要創建與非常相同的目的字符串一起工作

+0

是剛剛發現,但謝謝你的快速反應。 – user3749535

0

好吧,發佈後不久,我發現我做錯了什麼。我沒有意識到,當你創建你的保護器,你應該使用一個鍵....

_protector = provider.CreateProtector("KeyHere"); 
+0

該參數在文檔中被稱爲「目的字符串」......它不是密鑰......實際密鑰是從根密碼密鑰和所述目的字符串派生的...將解密移動到另一個系統並觀看它失敗,因爲另一組根密鑰...請參閱文檔... https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/purpose-strings – DarkSquirrel42

相關問題