Using FormsAuthentication.SetAuthCookie to store an Encrypted String - c#

I'll start by saying, maybe this is overkill.
During my login routine, I encrypt the user's login id prior to using FormsAuthentication.SetAuthCookie.
The problem is that if the encrypted string ends up having escape characters, the string that get saved gets truncated do to the escape characters.
Should I just abondone trying to encrypt the user's login id?
Or, is there a way to get around this issue?
Here is a sample string that gets truncated:
<< *€ƒKõ‹¯Þ\0ý´Gv\"þEaÔs0n×\tD¦™s€7Œ>>

When you encrypt the user id, you should use Base64 encoding so that the encrypted data will only contain valid characters (alphanumeric, +, /, =).
You would probably find this helpful: Convert.ToBase64String(byte[])
Example:
string userId = "Hello";
byte[] encryptedData = GetEncryptedBytes(userId);
string encodedUserId = Convert.ToBase64String(encryptedData);
// encodedUserId is "SGVsbG8="
FormsAuthentication.SetAuthCookie(encryptedUserId);
And decoding is the reverse:
string encodedUserId = "SGVsbG8=";
byte[] encryptedData = Convert.FromBase64String(encodedUserId);
string userId = GetDecryptedString(encryptedData);

Related

AES key converting to string and byte[] C#

I have an application that generates a AES Key (using Security.Cryptography). I take that AES Key, convert it to string and put it in a cookie like this:
string keyToSend = Encoding.UTF8.GetString(CurrentKey);
HttpCookie sessionKeyCookie = new HttpCookie("SessionKey", JsonConvert.SerializeObject(keyToSend));
keyToSend looks like this: "���K��Ui ����&��Ӂ*��()".
Then, I want to take back that key and use it to decrypt something, and I do this:
string keyString = JsonConvert.DeserializeObject<string>(context.Cookies["SessionKey"].Value);
byte[] ascii = Encoding.ASCII.GetBytes(cevaString);
byte[] utf8 = Encoding.UTF8.GetBytes(cevaString);
byte[] utf32 = Encoding.UTF32.GetBytes(cevaString);
Also, my keyToString looks like this: "���K��Ui ����&��Ӂ*��()".
And my browser cookie looks like this: "�\u0010��K��Ui �\u0010�\u000f�\u001f\u0005�\u0012\u0018&��Ӂ*��()\u001e"
The initial key should have 256bits, so 32 entries in that array, but all my variables (ascii, utf8, utf32) have different lengths. Why is that, how can I retrieve the cookie and convert it to a byte[32] array?
It sounds like CurrentKey is arbitrary binary data - not a UTF-8 encoded string. If you've got arbitrary data which you need to encode as a string (e.g. an image, or encrypted or compressed data) you're usually best off using Base64 or hex encoding. Base64 is pretty easy:
string keyToSend = Convert.ToBase64String(CurrentKey);
...
byte[] recoveredKey = Convert.FromBase64String(keyString);

Authentication from C# to MySQL CakePhp users

I'm currently migrating a CakePhp app to ASP.NET. One thing that is blocking me at this point is that I'm unable to get the right hashing method to get the right password fit so users are able to sign-in from the ASP.NET app.
I have the salt value that is set in config/core.php file.
I've googled to try to determined where to find which hashing algorithm is used, and was not able to find the right query or no result.
here is my C# method so far to hash the password.
public static string ToHash(this string password, string salt)
{
if (string.IsNullOrEmpty(password))
return "";
var provider = new SHA1CryptoServiceProvider();
var encoding = new UnicodeEncoding();
var bytes = provider.ComputeHash(encoding.GetBytes(salt + password));
return Encoding.UTF8.GetString(bytes);
}
I've tried to put the salt before or after the password, it's currently no matching at all, here is the hash password from the cakephp mysql database:
c7fb60ef77dbe3d1681a68e6741ee3a23cc1f41d
Here is what I have from my method
��3[v"���1�:�ѐ��
Not really sure where/how to solve this problem. Any help or hint would be appreciated.
Thanks
I have it!
At least it works for my configuration:
Find salt from Core.php (search for Security.salt in the file). Then, use this code (very similar to the question):
string input = textBox1.Text;
input = "your salt should be here" + input;
var provider = new SHA1CryptoServiceProvider();
var encoding = new UTF8Encoding();
var bytes = provider.ComputeHash(encoding.GetBytes(input));
sha1result.Text = Bin2Hex(bytes);
Helper for Bin2Hex is also here:
public static string Bin2Hex(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-", "");
}
It wasn't easy finding it, I searched through some of internet (no results!) and finally resorted to source-digging.
Don't have the Cake sources with me right now, but you should easily be able to look up Cake's hashing and salting method in the source.
The above differences in data look like Cake transforms the hash bytes into a string with the hash's bytes in hex base. Whatever the difference in the hash method, you'll have to convert the C# hash's result into such a string as well before comparing them (or go the other way and parse Cake's hex string and build a byte array out of it).

UTF8 encoded password Byte[] with SHA512 encryption to string conversion

I have created a web form in c# that accepts username and password and stores password in MSSQL 2005 db in 'image' format. The password is merged with salt, encoded in UTF8 and lastly it is applied with a SHA512 encryption. I want to be able to see the passwords in string format when I pull them up back from the database. How should my decrypt function be, if the following is how I encrypted the password? Is that possible? :
string loginID = "";//This will be stored in varchar format in MSSQL..(Unrelated to the question)
string password =""; //This is where I store password inputted by user.
Random r = new Random();
int salt = r.Next((int)Math.Pow(2, 16));
int verifyCode = r.Next((int)Math.Pow(2, 16));
string tmpPwd = password.ToLower() + salt.ToString();
UTF8Encoding textConverter = new UTF8Encoding();
byte[] passBytes = textConverter.GetBytes(tmpPwd);
byte[] hashedPWD = new SHA512Managed().ComputeHash(passBytes);
The value in hashedPWD is stored in MSSQL as image datatype and salt is stored as int.
You can't - that's what a hash function is, by definition - a one-way function. Up until the last line, you can get the password back, but after the hash function, all you can do is generate a second hash and compare the two to see if they've produced the same result, in which case you can presume that the source strings were the same.

Is this 64-bit Encoded?

All of the passwords in our User DB look like this where we have == at the end:
91F2FSEYrFOcabeHK/UfNw==
So how can I tell if this is 64-bit encoded? It has to be because I can decode using a decode 64-bit routine I have.
I am trying now to figure out how to decode a literal string to 64-bit..back to the xxxxxxxx== and here is my code:
string passwordToEncrypt = "test";
byte[] passwordToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(passwordToEncrypt);
result = Convert.ToBase64String(passwordToBytes);
Updated:
I need the text test to come out in Base64 with the == at the end.
you have a typo in there - so the above code does not compile, try
string passwordToEncrypte = "test";
byte[] passwordToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(passwordToEncrypte);
string result = Convert.ToBase64String(passwordToBytes);
result contains now a "Base64"-encoded password and end with "=="...
BUT the above code works only for passwords containing ASCII... if you want it to work with UTF8 passwords then change it to :
string passwordToEncrypte = "test";
byte[] passwordToBytes = Encoding.UTF8.GetBytes(passwordToEncrypte);
string result = Convert.ToBase64String(passwordToBytes);
to go back from Base64 to the original you need to do:
string Original = Encoding.UTF8.GetString (Convert.FromBase64String(result));
see http://msdn.microsoft.com/en-us/library/86hf4sb8.aspx
and http://msdn.microsoft.com/en-us/library/system.convert.tobase64string.aspx
and http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx
Base64 encoded string doesn't always end with a =, it will only end with one or two = if they are required to pad the string out to the proper length.For more details checkout following link
Padding

Encoding and decoding a string that may have slashes in it

I have strings like this:
RowKey = "Local (Automatic/Manual) Tests",
When I try to store in Windows Azure then this fails as I assume it does not accept the "/" as part of the row key.
Is there a simple way that I can encode the value before putting into RowKey?
Also once the data is in the table I get it out with the following:
var Stores = storeTable.GetAll(u => u.PartitionKey == "ABC");
Is there a simple way that I can get out the value of RowKey and decode it?
One possible way for handling is this by converting the PartitionKey and RowKey values in Base64 encoded string and save it. Later when you retrieve the values, you just decode it. In fact I have had this issue some days back in our tool and Base64 encoding was suggested to me on MSDN forums: http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/a20cd3ce-20cb-4273-a1f2-b92a354bd868. But again it is not fool proof.
I'm not familiar with Azure, so I don't know if there is an existing API for that. But it's not hard to code:
encode:
const string escapeChar='|';
RowKey.Replace(escapeChar,escapeChar+escapeChar).Replace("/",escapeChar+"S");
decode:
StringBuilder sb=new StringBuilder(s.Length);
bool escape=false;
foreach(char c in s)
{
if(escape)
{
if(c=='S')
sb.Append('/');
else if(c==escapeChar)
sb.Append(escapeChar);
else
throw new ArgumentException("Invalid escape sequence "+escapeChar+c);
}
else if(c!=escapeChar)
{
sb.Append(c);
escape=false;
}
else
escape=true;
return sb.ToString();
When a string is Base64 encoded, the only character that is invalid in an Azure Table Storage key column is the forward slash ('/'). To address this, simply replace the forward slash character with another character that is both (1) valid in an Azure Table Storage key column and (2) not a Base64 character. The most common example I have found (which is cited in other answers) is to replace the forward slash ('/') with the underscore ('_').
private static String EncodeToKey(String originalKey)
{
var keyBytes = System.Text.Encoding.UTF8.GetBytes(originalKey);
var base64 = System.Convert.ToBase64String(keyBytes);
return base64.Replace('/','_');
}
When decoding, simply undo the replaced character (first!) and then Base64 decode the resulting string. That's all there is to it.
private static String DecodeFromKey(String encodedKey)
{
var base64 = encodedKey.Replace('_', '/');
byte[] bytes = System.Convert.FromBase64String(base64);
return System.Text.Encoding.UTF8.GetString(bytes);
}
Some people have suggested that other Base64 characters also need encoding. According to the Azure Table Storage docs this is not the case.

Categories

Resources