4

Am am using IDataProtector to protect and unprotect within a controller without a problem. I can inject the protector and use it.

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

This then shows both the encrypted and decrypted "1"

I can then create a link and pass this to another action on the same controller

<a asp-controller="Home"
   asp-action="GetKey"
   asp-route-id="@Model.encryptedtext">
    Pass Key to getkey
</a>

This passes the encrypted data and allows me to decrypt in the GetKey action.

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

        test.originaltext = _protector.Unprotect(id);
        return View(test);
    }

If i then try to create a link and pass it to another controller.

 <a asp-controller="Key"
   asp-action="GetKeyController"
   asp-route-id="@Model.encryptedtext">
    Pass Key to other controller
</a>

It fails with the error

System.Security.Cryptography.CryptographicException: The payload was invalid

Any clues on to where i should look?

2 Answers 2

5

in you instance creation call ...

provider.CreateProtector(GetType().FullName)

you provide the current type's full name as a purpose string for the protector ...

you will need the protector and deprotector to be created with the very same purpose string to work together

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah just found that out, but thanks for your quick response.
0

Ok, Shortly after posting i found what i was doing wrong. I didnt realise that when you create your protector you should use a key....

 _protector = provider.CreateProtector("KeyHere");

1 Comment

that parameter is called a "purpose string" in the docs ... it is not the key ... the actual key is derived from the root cryptographic keys AND said purpose string ... move the decryption to another system and watch it fail, because of another set of root keys ... see docs ... learn.microsoft.com/en-us/aspnet/core/security/data-protection/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.