2

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?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Manight
  • 500
  • 5
  • 26

1 Answers1

3

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.)

Levi
  • 32,628
  • 3
  • 87
  • 88
  • OK, I'm sure the problem is related to the conversion as you say but still don't find the proper behaviour. I'll give it another try as you suggested and be back here to report. Thank for now – Manight Dec 17 '12 at 21:50
  • 3
    One other suggestion: if you're storing this in a cookie, consider using HttpServerUtility.UrlTokenEncode / UrlTokenDecode instead. These methods are very similar to ToBase64String / FromBase64String, but they are slightly tweaked so that they don't cause problems in cookies. (For example, the tweaked methods don't use the '=' character like regular Base64 does.) – Levi Dec 17 '12 at 22:10
  • I would upvote this 1 billion times if I could. Just spent an hour trying to figure this out and this question and answer did the trick. Thanks! – NinjaBomb Dec 23 '15 at 06:01