Manight
Manight

Reputation: 510

CryptographyException with MachineKey.UnProtect and Cookies in ASP net 4.5

I'm trying to substitute the deprecated Encode and Decode methods with the new MachineKey.Protect and Unprotect methods with ASP.NET 4.5. I used the old methods to encrypt and decrypt cookie values as well but now when calling the Unprotect menthod I have a CryptographyException.

I think this as something to do with trying to save in the cookie value a string representation of the binary data issued by the protect method.

Methods are straightforward:

Public Shared Function Encode(text As String) As String
   If String.IsNullOrEmpty(text) Then
        Return String.Empty
    End If
    Dim stream As Byte() = Encoding.Unicode.GetBytes(text)
    Dim encodedValue As Byte() = MachineKey.Protect(stream, "test")
    Return Encoding.Unicode.GetString(encodedValue)
End Function

Public Shared Function Decode(text As String) As String
    If String.IsNullOrEmpty(text) Then
        Return String.Empty
    End If
    Dim stream As Byte() = Convert.FromBase64String(text)
    Dim decodedValue = MachineKey.Unprotect(stream, "test")
    Return Encoding.Unicode.GetString(decodedValue)
End Function

Any hint on how to implement the new methods with cookie values? Or should I just stick to the deprecated encode/decode methods or some alternatives for cookie encoding?

Upvotes: 2

Views: 1561

Answers (1)

Levi
Levi

Reputation: 32828

The last line of your Encode method should read:

Return Convert.ToBase64String(encodedValue)

This way, it can be passed to your Decode method, in which you try to interpret the input as Base64 before passing it to the Unprotect method.

(FYI, if the data you're encrypting is Latin-based text like English, you may want to consider using Encoding.UTF8 instead of Encoding.Unicode. It will cause the encrypted payload to be a bit smaller.)

Upvotes: 3

Related Questions