使用FormsAuthentication.SetAuthCookie存储加密字符串

时间:2011-11-29 19:06:20

标签: c# formsauthentication

我首先要说的是,这可能有点过头了。

在我的登录例程中,我在使用FormsAuthentication.SetAuthCookie之前加密了用户的登录ID。

问题是如果加密的字符串最终有转义字符,则保存的字符串将被截断为转义字符。

我是否应该尝试加密用户的登录ID?

或者,有没有办法解决这个问题?

以下是截断的示例字符串: << *€ƒKõ

1 个答案:

答案 0 :(得分:2)

加密用户ID时,应使用Base64 encoding,以便加密数据只包含有效字符(字母数字, + / ,< KBD> = )。
您可能会发现这有用:Convert.ToBase64String(byte[])

示例:

string userId = "Hello";
byte[] encryptedData = GetEncryptedBytes(userId);
string encodedUserId = Convert.ToBase64String(encryptedData);
// encodedUserId is "SGVsbG8="

FormsAuthentication.SetAuthCookie(encryptedUserId);

解码是相反的:

string encodedUserId = "SGVsbG8=";
byte[] encryptedData = Convert.FromBase64String(encodedUserId);
string userId = GetDecryptedString(encryptedData);