Leveraging ASP.NET machineKey For Encrypting My Own Data

前端 未结 5 1748
天命终不由人
天命终不由人 2021-01-30 02:00

I have some data I want to encrypt in an ASP.NET MVC application to prevent users from tampering with it. I can use the Cryptography classes to do the actual encryption/decrypt

5条回答
  •  后悔当初
    2021-01-30 02:22

    If you're working with 3.5 or earlier you can avoid a lot of code and just do this:

    public static string Encrypt(string cookieValue)
    {
        return FormsAuthentication.Encrypt(new FormsAuthenticationTicket(1,
                                                                         string.Empty,
                                                                         DateTime.Now,
                                                                         DateTime.Now.AddMinutes(20160),
                                                                         true,
                                                                         cookieValue));
    }
    
    public static string Decrypt(string encryptedTicket)
    {
        return FormsAuthentication.Decrypt(encryptedTicket).UserData;
    }
    

    One of my colleagues talked me into it and I think it's fairly reasonable to do this for custom cookies, if not for general encryption needs.

提交回复
热议问题