Valkyry
Valkyry

Reputation: 147

How can i encrypt and decrypt my Cookies in ASP.NET

Hello as the titles says, I'm trying to pass my cookie over pages, but I need to encrypt them and on the specific page (Home.aspx) i need to decrypt it. anyone has any idea how to?

My Code so far, Login.aspx:

    HttpCookie UserCookie = new HttpCookie("Login");
    UserCookie.Value = txtUsername.Text;
    UserCookie.Expires = DateTime.Now.AddHours(2);
    Response.Cookies.Add(UserCookie);

Upvotes: 6

Views: 19524

Answers (2)

Asons
Asons

Reputation: 87191

You can use MachineKey.Protect/MachineKey.Unprotect

This sample code also uses Base64 conversion to avoid getting unexpected error for invalid characters in the cookie value.

MachineKey.Protect(Encoding.UTF8.GetBytes(cookieValue), "a token").FromBytesToBase64();

Encoding.UTF8.GetString(MachineKey.Unprotect(Request.Cookies(cookieName).Value.FromBase64ToBytes, "a token"));

Src: https://msdn.microsoft.com/en-us/library/system.web.security.machinekey.protect(v=vs.110).aspx


Note: The above methods is extension methods to overcome null exceptions

public string FromBytesToBase64(this byte[] b)
{
    return b == null ? "" :  Convert.ToBase64String(b);
}

public byte[] FromBase64ToBytes(this string s)
{
    return s == null ? null : Convert.FromBase64String(s);
}

Upvotes: 7

Jason
Jason

Reputation: 8640

I had to change LGSon's answer slightly so it worked for me.

Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes("your cookie value")))

Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String("your cookie value")))

Upvotes: 10

Related Questions