【问题标题】:Using FormsAuthentication.SetAuthCookie to store an Encrypted String使用 FormsAuthentication.SetAuthCookie 存储加密字符串
【发布时间】:2011-11-29 19:06:20
【问题描述】:

我首先要说,也许这有点矫枉过正。

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

问题在于,如果加密的字符串最终包含转义字符,则保存的字符串会被截断以处理转义字符。

我应该放弃尝试加密用户的登录 ID 吗?

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

这是一个被截断的示例字符串: >

【问题讨论】:

    标签: c# formsauthentication


    【解决方案1】:

    加密用户ID时,应使用Base64 encoding,这样加密后的数据将只包含有效字符(字母数字、+/ =)。
    您可能会发现这很有帮助: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);
    

    【讨论】:

    • 当我尝试解密字符串时,这对我有什么影响?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2022-11-18
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    相关资源
    最近更新 更多