在ASP net 4.5中使用MachineKey.UnProtect和Cookies进行CryptographyException

时间:2012-12-16 16:04:26

标签: cookies encode asp.net-4.5

我正在尝试使用ASP.NET 4.5替换已弃用的EncodeDecode方法以及新的MachineKey.ProtectUnprotect方法。我也使用旧方法来加密和解密cookie值,但现在在调用Unprotect menthod时我有一个CryptographyException

我认为这与尝试在cookie值中保存由protect方法发出的二进制数据的字符串表示有关。

方法很简单:

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

有关如何使用cookie值实现新方法的任何提示?或者我应该坚持使用已弃用的编码/解码方法或cookie编码的其他替代方法吗?

1 个答案:

答案 0 :(得分:3)

Encode 方法的最后一行应为:

Return Convert.ToBase64String(encodedValue)

这样,它可以传递给 Decode 方法,在该方法中,在将输入传递给 Unprotect 方法之前,您尝试将输入解释为Base64。

(仅供参考,如果您要加密的数据是基于拉丁语的文本,如英语,您可能需要考虑使用 Encoding.UTF8 而不是 Encoding.Unicode 。它会使加密的有效载荷变小。)