Problem Encrypting a cookie using Handmade Encryption (ASP.NET)
I got a weird problem:
I am encrypting the content of the cookie.
My code works fine when I run it in Visual Studio, but it gives me "Bad request, HTTP error 400. The request is badly formed." when i run it from server.
Here is the class for Encrypt Cook.cs, located in app_code:
public class EncryptCook
{
public EncryptCook()
{
//
// TODO: Add constructor logic here
//
}
public string EncryptString(string data)
{
try
{
string encryptString = "";
if (data != "")
{
char a;
int key = Convert.ToInt16(DateTime.Now.Day);
int j = 0;
for (int i = 0; i < data.Length; i++)
{
j = (int)data[i];
j = j + key;
a = (char)j;
encryptString = encryptString + Convert.ToString(a);
}
}
return encryptString;
}
catch
{
return "";
}
}
public string DeEncryptString(string data)
{
try
{
string encryptString = "";
if (data != "")
{
char a;
int j = 0;
int key = Convert.ToInt16(DateTime.Now.Day);
for (int i = 0; i < data.Length; i++)
{
j = (int)data[i];
j = j - key;
a = (char)j;
encryptString = encryptString + Convert.ToString(a);
}
}
return encryptString;
}
catch
{
return "";
}
}
Quite simply, it takes a string, extracts characters from it and replaces the character with another, for example with the date "a", and that today's date is 13, it will replace it with the 13th character after "a", i.e. "m".
Here is my login control:
protected void Button1_Click (object sender, EventArgs e)
{
// code for retrieving user, which works fine
EncCook cook = new EncCook ();
HttpCookie cookie = new HttpCookie ("loginstatus");
cookie ["userid"] = cook.EncryptString (name);
cookie ["username"] = cook.EncryptString (doctor);
cookie ["email"] = cook.EncryptString (email);
cookie ["address"] = cook.EncryptString (address);
Response.Cookies.Add (cookie);
}
Well, this code works fine on local machine, but gives me "HTTP request error with error 400. Request badly formed". error.
I think this is because of the encoding, but I'm not sure how if its 20 today, then ~ + 20 would look like a field character.
thanks
a source to share
Please do not use encryption at home. It can only end in embarrassment. And if you catch an exception, you should probably rebuild it, or return null, not an empty string. The error is most likely because your so-called encryption creates sequences of bytes that are not valid in the current encoding.
a source to share