user3749535
user3749535

Reputation: 53

Encrypt Decrypt with Data Protection in c# MVC across controllers

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?

Upvotes: 4

Views: 3369

Answers (2)

user3749535
user3749535

Reputation: 53

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

Upvotes: 0

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

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

Upvotes: 5

Related Questions