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?