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

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")))

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);
}