Encrypt cookies in ASP.NET
Why not just use the encryption found in System.Security.Cryptography to encrypt and decrypt the cookie name and value when it's sensitive? You can write some utility functions to manage it pretty easily. Example utility functions:
private static void SetEncryptedCookie(string name, string value)
{
var encryptName = SomeEncryptionMethod(name);
Response.Cookies[encryptName].Value = SomeEncryptionMethod(value);
//set other cookie properties here, expiry &c.
//Response.Cookies[encryptName].Expires = ...
}
private static string GetEncryptedCookie(string name)
{
//you'll want some checks/exception handling around this
return SomeDecryptionMethod(
Response.Cookies[SomeDecryptionMethod(name)].Value);
}
How can i encrypt and decrypt my Cookies in ASP.NET
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);
}
Secure cookies Asp.Net Core
There are several ways to encrypt and decrypt string and simple one of them is using IDataProtector
.
private IDataProtector _protector;
public AccessController(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("MySecretKey");
}
public void ActionResult Index()
{
var protectedName = _protector.Protect("Tom");
HttpContext.Response.Cookies.Append("name", protectedName);
.
.
.
}
and use _protector.UnProtect(encryptedString)
to decrypt string.
safe and secure HTTPCookie storage in ASP.NET MVC C# application
You can use the Protect and Unprotect methods to encrypt cookies. Note that both bytes have the same key value. Data encrypted with Protect can only be decrypted with Unprotect.
encrypted method
public string encryptedCookie(string value)
{
var cookieText = Encoding.UTF8.GetBytes(value);
var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, "ProtectCookie"));
return encryptedValue;
}
decrypted method
public string decryptedCookie(string value)
{
var bytes = Convert.FromBase64String(value);
var output = MachineKey.Unprotect(bytes, "ProtectCookie");
string result = Encoding.UTF8.GetString(output);
return result;
}
Instead of "ProtectCookie"
, you can use your unique key.
How to encrypt cookies in ASP mvc3?
Are you using the credentials to log in the user for each request? I think you should reconsider your strategy, to do an authorization once, and then use something like FormsAuthentication which would create an encrypted session cookie which would contain the user identity.
Then you do not need to keep logging in the user, and you wouldn't need to worry about encrypting a standard cookie either (which is a very dangerous approach anyway).
For e.g. your login handling code could do:
string username = // get username;
string password = // get password;
bool rememberMe = // get remember me setting.
if (YourAuthenticationSystem.Authenticate(username, password))
{
FormsAuthentication.SetAuthCookie(username, rememberMe);
}
As you can see, this method has support for a 'remember me' option.
You will need the web.config code:
<authentication mode="Forms">
<forms name="TheNameOfYourAuthCookie" loginUrl="http://yourdomain.com/Login" path="/" domain="" timeout="40320" slidingExpiration="true" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
Read more about FormsAuthentication here: http://msdn.microsoft.com/en-us/library/xdt4thhy(v=vs.100).aspx
Protecting Cookies in ASP.NET and SSL
Does this mean that I don't have to worry about encrypting the cookies explicitly using the methods outlined in the following links in order to protect them?
That will greatly depend on what information you are storing in those cookies and whether you care about the user being able to manipulate it. For example FormsAuthentication cookies are always encrypted because they contain the currently authenticated username. If they weren't encrypted the user could simply forge a request and replace his username with for example admin
. The fact that the cookie is sent over SSL is absolutely not an obstacle for him.
On the other hand if you are storing some user preferences such as background theme, you probably wouldn't care if the user forges a request in which he changes his background color from blue to red, right?
So to conclude: if you don't want the user to be able to modify the value of the cookie you should encrypt it, no matter whether it is sent over SSL or not.
SSL is used to protect from man-in-the-middle attacks in which the end user cookie value could be stolen by a man-in-the-middle.
Related Topics
Quartz.Net Setup in an ASP.NET Website
Passing Command Line Parameters with Visual Studio C#
Is CSV with Multi Tabs/Sheet Possible
Catching Unhandled Exception on Separate Threads
Add Vertical Scroll Bar to Panel
How to Initialize a Datetime Field
Using Webclient or Webrequest to Login to a Website and Access Data
Synchronize Scroll Position of Two Richtextboxes
JSON.Net: Specify Converter for Dictionary Keys
Async Await VS Getawaiter().Getresult() and Callback
Binding Selecteditems of Listview to Viewmodel
Advantage of Using Thread.Start VS Queueuserworkitem
Why Is Foreach Loop Read-Only in C#
C# String Replace with Dictionary