如何在ASP.NET网站中加密查询字符串参数?

Hem*_*yal 11 asp.net encryption query-string

在我的一个ASP.Net网站中,我必须提供一个指向用户的链接,其中所有查询字符串参数都应加密.

我在想的是使用命令"aspnet_regiis"(用于加密web.config数据),将输出作为查询字符串传递到已发布的U​​RL中.

当用户单击该链接时,我首先解密该字符串,然后获取查询字符串的原始数据.

我这样做是对的吗?是否有任何好的技术来加密和解密查询字符串?

Sim*_*ier 6

在ASP.NET上下文中加密和解密字符串的一种好方法是使用FormsAuthentication.Encrypt方法

它似乎只适用于cookie,但它在其他上下文中运行良好,此外,您还可以添加到期日期(如果不需要,还可以添加DateTime.MaxValue),这是一个示例代码:

public static string Encrypt(string content, DateTime expiration)
{
    return FormsAuthentication.Encrypt(new FormsAuthenticationTicket(1,
        HttpContext.Current.Request.UserHostAddress, // or something fixed if you don't want to stick with the user's IP Address
        DateTime.Now, expiration, false, content));
}

public static string Decrypt(string encryptedContent)
{
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedContent);
    if (!ticket.Expired)
            return ticket.UserData;

    return null; // or throw...
}
Run Code Online (Sandbox Code Playgroud)